[Haskell-cafe] defining last using foldr

Rodrigo Queiro overdrigzed at gmail.com
Tue Aug 14 17:16:25 EDT 2007


You can consider foldr to be continual modification of a state. The
initial state is given as an argument, and then the (a -> b -> b)
function is passed the next element of the list and the current state,
and it returns the new state. foldr will then return the final state,
from which the result can be extracted. Does that help?

On 14/08/07, Alexteslin <alexteslin at yahoo.co.uk> wrote:
>
> 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?
>
>
> Aaron Denney wrote:
> >
> > On 2007-08-14, Alexteslin <alexteslin at yahoo.co.uk> wrote:
> >>
> >> Hi,
> >>
> >> I am trying to do the exercise which asks to define built-in functions
> >> 'last' and 'init' using 'foldr' function, such as last "Greggery Peccary"
> >> =
> >> 'y'
> >>
> >> the type for my function is:
> >>
> >> myLast :: [Char] -> Char
> >>
> >> I am not generalizing type so that make it less complicated.  But what
> >> ever
> >> i am trying would not work.  The only function type foldr takes as an
> >> argument is either (a->a->a) or (a->b->b) and none of the functions i
> >> found
> >> that would match this type from Char to Char.  So in other words should
> >> be
> >> (Char->Char-Char).  I can define the function without foldr but that
> >> misses
> >> the point of the exercise.
> >
> > 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 []).
> >
> > --
> > Aaron Denney
> > -><-
> >
> > _______________________________________________
> > Haskell-Cafe mailing list
> > Haskell-Cafe at haskell.org
> > http://www.haskell.org/mailman/listinfo/haskell-cafe
> >
> >
>
> --
> View this message in context: http://www.nabble.com/defining-last-using-foldr-tf4269357.html#a12151694
> Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list