[Haskell-cafe] Re: defining last using foldr
wnoise at ofb.net
Tue Aug 14 17:33:39 EDT 2007
(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
I didn't say to use (:), I said foldr works by replacing (:) with some
foldr also takes a function of type (a -> b -> b).
foldr f e
(first : (middle : (last : )))
(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
More information about the Haskell-Cafe