[Haskell-cafe] How to write fast for loops

Daniel Trstenjak daniel.trstenjak at gmail.com
Tue Apr 29 07:36:00 UTC 2014


On Tue, Apr 29, 2014 at 04:39:35AM +0100, Niklas Hambüchen wrote:
> Current most appealing solution for fast loops
> ----------------------------------------------
> 
> Unfortunately, this seems to be the most robustly fast (across all types
> I have tested it with) loop:
> 

>   forLoop :: (Monad m) => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
>   forLoop start cond inc f = go start
>     where
>       go !x | cond x    = f x >> go (inc x)
>             | otherwise = return ()

Regarding the used stack space, wouldn't the following solution be even better?


forLoop :: (Monad m) => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forLoop start cond inc f = go start (return ())
  where
    go !x m | cond x    = go (inc x, m >> f x)
            | otherwise = m


Greetings,
Daniel


More information about the Haskell-Cafe mailing list