[Haskell-cafe] defining last using foldr
ok at cs.otago.ac.nz
Thu Aug 16 21:03:20 EDT 2007
Let's start by reminding ourselves what foldr does.
foldr f z [x1,x2,...,xn] = f x1 (f x2 ... (f xn z) ...)
Now let's ask about last:
last  = error ...
last [x1,...,xn] = xn
We're going to have to keep track of whether we have a last element
or not. The obvious candidate for this is Maybe x. Initially there
is no element, Nothing.
f x Empty = Just x
f x (Just y) = Just y
This picks up a new value (x) when there wasn't one (Nothing) and
keeps the old last element (Just y) when there was one (Just y).
But this gives us a Maybe x, when we want an x, so we'll have to finish
off with a fromJust.
last = fromJust . foldr f Nothing
where f _ r@(Just _) = r
f x Nothing = Just x
More information about the Haskell-Cafe