[Haskell-cafe] Foldl

Donald Bruce Stewart dons at cse.unsw.edu.au
Fri Nov 24 06:34:12 EST 2006


zacara:
> 
> Hello,
> 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.
> An example:
> input: [1,2,3,4]
> output: [(1,0)(2,1)(3,3)(4,6)]
> 

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).

-- Don


More information about the Haskell-Cafe mailing list