[Haskell-cafe] defining last using foldr
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
>> 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
> other function.
> 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
> Aaron Denney
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
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