[Haskell-cafe] How to write fast for loops

Niklas Hambüchen mail at nh2.me
Sat Apr 26 21:40:50 UTC 2014


As you probably now, `forM_ [1..n]` is incredibly slow in Haskell due to
lack of list fusion [1]; a manually written loop is 10x faster.

How do you people work around this?

I keep defining myself something like

  loop :: (Monad m) => Int -> (Int -> m ()) -> m ()
  loop bex f = go 0
    where
      go !n | n == bex  = return ()
            | otherwise = f n >> go (n+1)

Is there a function for this somewhere already?
Or do you have another way to deal with this problem?

Thanks!


[1]: https://ghc.haskell.org/trac/ghc/ticket/8763


More information about the Haskell-Cafe mailing list