[Haskell-beginners] replacing fold with scan!
Brent Yorgey
byorgey at seas.upenn.edu
Thu May 1 17:00:28 UTC 2014
On Thu, May 01, 2014 at 12:31:38PM +0800, Zhi An Ng wrote:
>
> So to get this to work, you need to change the type signature of filter''
>
> filter'' :: (a -> Bool) -> [a] -> [[a]]
Well, but that is not filter, is it? It is possible to define the
original filter using scanr, but you have to do a little
postprocessing of the output of scanr.
-Brent
>
>
> On Thu, May 1, 2014 at 10:42 AM, raffa f <freitasraffa at gmail.com> wrote:
>
> > hi everyone! here's my new problem. i wrote my version of filter:
> >
> > filter' :: (a -> Bool) -> [a] -> [a]
> > filter' f = foldr (\x acc -> if f x then x:acc else acc) []
> >
> > and it works! however, i wanted to use scan too. so i just replaced foldr
> > with scanr, to see what would happen:
> >
> > filter'' :: (a -> Bool) -> [a] -> [a]
> > filter'' f = scanr (\x acc -> if f x then x:acc else acc) []
> >
> > but that doesn't work! ghci gives me this:
> >
> > folds.hs:15:59:
> > Couldn't match expected type `a' with actual type `[a0]'
> > `a' is a rigid type variable bound by
> > the type signature for filter'' :: (a -> Bool) -> [a] -> [a]
> > at folds.hs:14:13
> > In the second argument of `scanr', namely `[]'
> > In the expression:
> > scanr (\ x acc -> if f x then x : acc else acc) []
> > In an equation for filter'':
> > filter'' f = scanr (\ x acc -> if f x then x : acc else acc) []
> > Failed, modules loaded: none.
> >
> > the problem seems to be with the start value of [], it seems? i don't
> > understand, i thought scan and fold worked pretty much the same. i learned
> > about these functions today, so i'm still trying to wrap my head around
> > them...
> >
> > thank you!
> >
> > _______________________________________________
> > Beginners mailing list
> > Beginners at haskell.org
> > http://www.haskell.org/mailman/listinfo/beginners
> >
> >
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
More information about the Beginners
mailing list