David Roundy wrote:
stats elems = foldl add_elem Map.empty elems
add_elem m x = Map.insertWith (+) x 1 m

main = print $ stats $ take 1000000 $ repeat 1

This program has a space leak and runs out of stack space.  I'm guessing
that I'm being bit here by an unnatural amount of laziness in
Map.insertWith, but I can't see how to fix this.  :(  I'm sure it's
something elementary...

try:

stats = foldl' add_elem Map.empty
add_elem m x = myinsertWith (+) x 1 m

myinsertWith f k v m =
  case Map.lookup k m of
        Nothing -> Map.insert k v m
        Just w -> let r = f v w in r `seq` Map.insert k r m

main = print $ stats $ take 1000000 $ repeat 1
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to