[Haskell-cafe] defining last using foldr

Alexteslin alexteslin at yahoo.co.uk
Wed Aug 15 16:24:52 EDT 2007

Aaron Denney wrote:
> (Quoting reformatted.  Try to have your responses below what you are
> responding to.  It makes it easier to read as a conversation.)
> On 2007-08-14, Alexteslin <alexteslin at yahoo.co.uk> wrote:
>> Aaron Denney wrote:
>>> Folds replace the "cons" operator (:) with the function you pass it.
>>> If you want the tail of the list, you want what is on the right hand
>>> side of every cons (unless that's []).
>> Well, i have tried cons (:) operator but when it passed to foldr doesn't
>> work
>> because cons operator operates first character and then the list but the
>> foldr argument takes a function (a->a->a).  Maybe i am missing the point
>> here?
> I didn't say to use (:), I said foldr works by replacing (:) with some
> other function.
> foldr also takes a function of type (a -> b -> b).
> foldr f e 
> replaces
> (first : (middle : (last : [])))
> with
> (first `f` (middle `f` (last `f` e)))
> You want last to be kept, so 
> f x e = x
> this causes the overall pattern to reduce to
> (first `f` (middle `f` last))
> This time you need
> f y last = last
> This means you need to discriminate between "e" and "last".
> If you make "e" the same type as last, you could accidentally compare
> them equal.  So instead of using the same type, we want one with one
> more value.  There is a standard one: "Maybe a", with constructors
> "Just a" and "Nothing".  And you also need to promote last to this
> type with the constructor Just, because the result gets fed in on the
> right.
> -- 
> Aaron Denney
> -><-
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

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

View this message in context: http://www.nabble.com/defining-last-using-foldr-tf4269357.html#a12169661
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

More information about the Haskell-Cafe mailing list