HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Moduleloop-0.3.0Haskell98

Control.Loop

Provides a convenient and fast alternative to the common forM_ [1..n] idiom, which in many cases GHC cannot fuse to efficient code.

Notes on fast iteration:

  • For Int, (+1) is almost twice as fast as succ because succ does an overflow check.

  • For Int, you can get around that while still using Enum using toEnum . (+ 1) . fromEnum.

  • However, toEnum . (+ 1) . fromEnum is slower than succ for Word32 on 64-bit machines since toEnum has to check if the given Int exceeds 32 bits.

  • Using (+1) from Num is always the fastest way, but it gives no overflow checking.

  • Using forLoop you can flexibly pick the way of increasing the value that best fits your needs.

  • The currently recommended replacement for forM_ [1..n] is forLoop 1 (<= n) (+1).

  • 6 values
  • Packageloop-0.3.0
  • Exports6
  • LanguageHaskell98
  • LicenceMIT
  • SourceLoop.hs
valueforLoop :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
#

forLoop start cond inc f: A C-style for loop with starting value, loop condition and incrementor.

valueforLoopState
  1. :: Monad m
  2. => a
  3. -> a -> Bool
  4. -> a -> a
  5. -> b
  6. -> b -> a -> m b
  7. -> m b
#

forLoopState start cond inc initialState f: A C-style for loop with starting value, loop condition, incrementor and a state that is threaded through the computation.

valueforLoopFold
  1. :: a
  2. -> a -> Bool
  3. -> a -> a
  4. -> acc
  5. -> acc -> a -> acc
  6. -> acc
#

forLoopFold start cond inc acc0 f: A pure fold using a for loop instead of a list for performance.

Care is taken that acc0 not be strictly evaluated if unless done so by f.

valuenumLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()
#

numLoop start end f: Loops over a contiguous numerical range, including end.

Does nothing when not start <= end.

It uses (+ 1) so for most integer types it has no bounds (overflow) check.

valuenumLoopState
  1. :: (Num a, Eq a, Monad m)
  2. => a
  3. -> a
  4. -> b
  5. -> b -> a -> m b
  6. -> m b
#

numLoopState start end f initialState: Loops over a contiguous numerical range, including end threading a state through the computation.

It uses (+ 1) so for most integer types it has no bounds (overflow) check.

valuenumLoopFold :: (Num a, Eq a) => a -> a -> acc -> (acc -> a -> acc) -> acc
#

numLoopFold start end acc0 f: A pure fold over a contiguous numerical range, including end.

It uses (+ 1) so for most integer types it has no bounds (overflow) check.

Care is taken that acc0 not be strictly evaluated if unless done so by f.