[Haskell-cafe] defining last using foldr

Kurt Hutchinson kelanslists at gmail.com
Fri Aug 17 10:04:50 EDT 2007

On 8/16/07, ok <ok at cs.otago.ac.nz> wrote:
> 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

I had this idea as well, but the questioner said the chapter with the
exercise preceded any use of Maybe, although I admit my suggestion of
using foldr to compose a processing function is more complicated for a
beginner. Here's a way to use the above idea without Maybe:

myLast = head . foldr f []
    f x [] = [x]
    f _ [x] = [x]

More information about the Haskell-Cafe mailing list