[Haskell-cafe] Foldl

Marco Comini comini at dimi.uniud.it
Fri Nov 24 16:27:28 EST 2006

Donald Bruce Stewart:
>  zacara:
>  > i'd like to write a function that given a list like [1,2,3,4...]
>  > returns a list of couple where the first element is the corresponding
>  > element of the string, and the second is the sum of the previous
>  > elements.
>  Looks like a scanl (a prefix fold) -- the "of the previous
>  elements" is a clue that you're describing a scan:
>      Prelude> :t scanl
>      scanl :: (a -> b -> a) -> a -> [b] -> [a]
>      Prelude> scanl (+) 0 [1..4]
>      [0,1,3,6,10]
>  You should be able to work out the rest from here (or rewrite it as a
>  fold).

I agree Don,
	certainly with scanl one can solve the problem elegantly.
[For ClareZako: it could be something like
   f (x:xs) = scanl acc (x,0) xs
       acc (x,s) y = (y, s+x)
On the contrary a solution in terms of a fold is indeed more tricky. 
Probably ClareZako was actually looking for a solution in term of a 
scan instead of a fold... otherwise would be interesting to know why 
he's willing to solve this problem in such a twisted way... don't you 


More information about the Haskell-Cafe mailing list