TExcelTAD
Home › Haskell › Haskell Strictness

Haskell Strictness

Laziness is Haskell's default, but it is not always what you want. When a value will certainly be needed, delaying it only creates thunks, and a long chain of thunks can waste memory or even overflow the stack. This lesson shows how to make evaluation strict where it matters: seq, $!, bang patterns, foldl' and strict data fields.

The space leak in a lazy accumulator

Consider summing with a plain foldl:

text
foldl (+) 0 [1, 2, 3, 4]
= foldl (+) (0 + 1) [2, 3, 4]
= foldl (+) ((0 + 1) + 2) [3, 4]
= foldl (+) (((0 + 1) + 2) + 3) [4]
= ((((0 + 1) + 2) + 3) + 4)          -- only now is anything added

The accumulator grows into a nested expression with one thunk per element. For a list of ten million numbers that is ten million thunks in memory before a single addition happens. (With optimisation turned on GHC often spots and fixes this, but you should not rely on it.)

seq: evaluate this first

seq a b evaluates a (to weak head normal form, see below) and then returns b. It is the primitive that all strictness tools are built on:

haskell · try it yourself
sumStrict :: [Int] -> Int
sumStrict = go 0
  where
    go acc [] = acc
    go acc (x : xs) = let acc' = acc + x in acc' `seq` go acc' xs

main :: IO ()
main = do
  print (sumStrict [1 .. 5000000])
  print (seq (1 + 1) "seq returns its second argument")
  print (const "lazy const ignores its argument" (undefined :: Int))
12500002500000
"seq returns its second argument"
"lazy const ignores its argument"

Now each new accumulator is computed before the recursive call, so the function runs in constant memory.

$!, bang patterns and foldl'

Writing seq by hand is clumsy, so there are shortcuts:

Tool Meaning
f $! x evaluate x, then call f x (strict application)
go !acc (x : xs) = … a bang pattern: evaluate acc when the equation is entered
foldl' a left fold that forces the accumulator at every step
data P = P !Int !Int strict fields: evaluated when the constructor is built
modifyIORef', Map.insertWith from Data.Map.Strict strict versions of common functions
haskell · try it yourself
import Data.List (foldl')

mean :: [Double] -> Double
mean xs = total / fromIntegral count
  where
    (total, count) = foldl' step (0, 0 :: Int) xs
    step (!s, !c) x = (s + x, c + 1)

countIf :: (a -> Bool) -> [a] -> Int
countIf p = go 0
  where
    go !n [] = n
    go !n (y : ys) = go (if p y then n + 1 else n) ys

main :: IO ()
main = do
  print (foldl' (+) 0 [1 .. 5000000 :: Int])
  print (mean (map fromIntegral [1 .. 1000000 :: Int]))
  print (countIf even [1 .. 3000000 :: Int])
  print (negate $! 5)
12500002500000
500000.5
1500000
-5

Note the bang patterns inside the tuple pattern in step: foldl' only forces the accumulator tuple itself, not the numbers inside it.

Weak head normal form

seq and the bang patterns evaluate a value only to weak head normal form (WHNF): just far enough to see its outermost constructor. For a number that means fully evaluated. For a pair, a list or a Just, it means "we know it is a pair / a cons cell / a Just", while the contents may still be thunks:

haskell · try it yourself
main :: IO ()
main = do
  let pair = (undefined, 2) :: (Int, Int)
      list = [undefined, undefined] :: [Int]
      maybeV = Just undefined :: Maybe Int
  pair `seq` putStrLn "pair is in WHNF: its components were not touched"
  list `seq` putStrLn "list is in WHNF: only the first cons cell was checked"
  maybeV `seq` putStrLn "Just _ is in WHNF"
  print (snd pair, length list)
pair is in WHNF: its components were not touched
list is in WHNF: only the first cons cell was checked
Just _ is in WHNF
(2,2)

To evaluate a structure completely (normal form), the deepseq package provides deepseq and force. It ships with GHC as a boot package, so it works here:

haskell · try it yourself
import Control.DeepSeq (force, deepseq)
import Control.Exception (evaluate, try, ErrorCall (..))

main :: IO ()
main = do
  let fine = [1, 2, 3] :: [Int]
      broken = [1, undefined, 3] :: [Int]
  fine `deepseq` putStrLn "fully evaluated without problems"
  r <- try (evaluate (force broken))
  case r of
    Left (ErrorCall msg) -> putStrLn ("deep evaluation hit: " ++ msg)
    Right xs -> print xs
fully evaluated without problems
deep evaluation hit: Prelude.undefined

Strict data fields

A ! in front of a field type makes the field strict: whenever the constructor is evaluated, the field is evaluated too. It is a simple, effective way to stop thunks from piling up inside long-lived data such as counters and accumulators:

haskell · try it yourself
import Data.List (foldl')

data Stats = Stats {count :: !Int, total :: !Double, biggest :: !Double}
  deriving Show

addSample :: Stats -> Double -> Stats
addSample (Stats c t b) x = Stats (c + 1) (t + x) (max b x)

main :: IO ()
main = do
  let samples = map (\i -> fromIntegral (i `mod` 97)) [1 .. 2000000 :: Int]
      s = foldl' addSample (Stats 0 0 0) samples
  print s
  print (total s / fromIntegral (count s))
Stats {count = 2000000, total = 9.5998893e7, biggest = 96.0}
47.9994465

Because foldl' forces each new Stats to WHNF and the fields are strict, every number is computed immediately.

Tip: A good default for application code: make fields of records strict (!), use Data.Map.Strict, foldl' and modifyIORef', and leave everything else lazy. Laziness is still valuable for control flow and infinite structures; strictness is for accumulated data.

Test yourself

What does seq a b do?

  1. Returns a
  2. Evaluates a to weak head normal form, then returns b
  3. Runs a and b in parallel
  4. Fully evaluates both

Does seq (undefined, 1) "ok" crash?

  1. Yes, undefined is evaluated
  2. No: WHNF of a pair only checks that it is a pair
  3. It is a type error
  4. Only with optimisation

Which fold avoids building a chain of thunks in the accumulator?

  1. foldl
  2. foldl'
  3. foldr
  4. scanl