[Haskell-cafe] Re: defining last using foldr

Jon Fairbairn jon.fairbairn at cl.cam.ac.uk
Wed Aug 15 16:42:45 EDT 2007

Alexteslin <alexteslin at yahoo.co.uk> writes:

> I am really sorry, but i still can't define the function.  The chapter the
> exercise is in precedes algebraic types or Maybe a types.  And is seems that
> must being easy to define. 
> I answered some exercises on using foldr such as summing for example, but
> this one i am trying:
> myLast :: [Int] -> Int
> myLast (x:xs) = foldr (some function) x xs.  
> With summing as i understood foldr goes through the list and sums up by (+)
> operator and one argument like 0.  Like: foldr (+) 0 xs

You can think of foldr f e [a,b,c] as

a `f` (b `f` (c `f` e))

so myLast [x,a,b,c] is going to be a `f` (b `f` (c `f` x))

so you need an f so that c `f` x is c (for any c and x) and
yet (b `f` c) is c for any c and b -- this is impossible (or
I'm asleep). So your skeleton above isn't going to work.

You can do something like 

myLast l = unpick (foldr toLast [] l)
           where unpick ...
                 toLast ...

The above contains a strong hint as to the type of toLast (and hence unpick)

Jón Fairbairn                                 Jon.Fairbairn at cl.cam.ac.uk

More information about the Haskell-Cafe mailing list