[Haskell-cafe] working with lists of couples
J. Garrett Morris
trevion at gmail.com
Sat Nov 18 03:44:41 EST 2006
On 11/17/06, Henning Thielemann <lemming at henning-thielemann.de> wrote:
> On Fri, 17 Nov 2006, Clara Zamolo wrote:
> > buildCouples = snd . foldl op (0,[])
> > where
> > op (v,xs) x = (v+x,xs++[(x,v)])
> >
You could make something like this that doesn't have quadratic-type
appends by accumulating functions instead of lists:
Prelude> snd (foldl (\(s,f) x -> (x+s,f . ((x,s):))) (0,id) [1..6]) []
[(1,0),(2,1),(3,3),(4,6),(5,10),(6,15)]
but this is better:
> I suggest using 'scanl' and then 'zip' the result together with the
> original list.
Or, equivalently, use mapAccumL from the Data.List library:
Prelude Data.List> snd $ mapAccumL (\s x -> (s + x,(x,s))) 0 [1..6]
[(1,0),(2,1),(3,3),(4,6),(5,10),(6,15)]
/g
More information about the Haskell-Cafe
mailing list