[Haskell-cafe] Grouping - Map / Reduce

jean-christophe mincke jeanchristophe.mincke at gmail.com
Fri Mar 27 06:50:30 EDT 2009


Hello

What do you think of this?  There is perhaps a recursive call that should be
made tail recursive but it seems to work.

The 'group' function takes the list of pairs as input and outputs a list of
maps from key to sums.

The nth element of the list of maps corresponds to the grouping applied for
the elements 0....n of the input list of pairs. Thus, that also works on
infinite list.

Unless I am missing sth...


import Data.Map (Map)
import qualified Data.Map as Map

group :: [(Int,Int)]  -> Map Int Int ->  [Map Int Int]
group [] amap  = []
group ((k, v):t) amap  = newmap : group t newmap
                                  where
                                 newmap = (Map.insertWith (+) k v amap)

l = [(1,1), (2,10), (1,2), (2,11), (1,3), (2,12)]

r = group l Map.empty

rr = take 2 r

li = concat [ [(1,i), (2, 10*i)] | i <- [0..] ]
ri = group li Map.empty

rri = take 20 ri


Regards

J-C



> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090327/11613f7b/attachment.htm


More information about the Haskell-Cafe mailing list