[Haskell-cafe] defining last using foldr

Kurt Hutchinson kelanslists at gmail.com
Thu Aug 16 14:09:26 EDT 2007


On 8/15/07, Alexteslin <alexteslin at yahoo.co.uk> wrote:
> 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

I don't think you can do it directly using just foldr. However, you
can use foldr to build up a function that, when applied to the list,
will evaluate to the last element. foldr will be acting like a
function composition engine that evaluates to a function to process
the list.

I got the idea for this from the article titled "Getting a Fix from
the Right Fold" in The Monad Read Issue 6
(http://www.haskell.org/sitewiki/images/1/14/TMR-Issue6.pdf). See if
reading that article helps. In particular, Solution 2 described in the
article is the one with the structure I'm talking about. (Solution 3
fixes a space leak in Solution 2, if you want a bit more complexity.)


More information about the Haskell-Cafe mailing list