Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 57 ยท Laziness and purity

Strictness, Bang Patterns and seq

Learn why lazy accumulators leak memory in Haskell and how foldl', seq, bang patterns, strict fields and deepseq force evaluation at the right time.

Lazy evaluation is a gift until a program quietly builds a million unevaluated additions and runs out of memory. That is a space leak: memory held by thunks that could have been computed already. The remedy is strictness, which means forcing a value at a chosen moment.

This lesson explains the classic foldl versus foldl' problem, then shows the tools Haskell gives you: seq, bang patterns, strict fields and deepseq. The real Haskell blocks are read-only; the stand-ins use JavaScript to make the idea of "a chain of delayed operations" visible.

How a space leak happens

Add up the numbers from 1 to n with a lazy left fold:

HASKELL
total :: Integer
total = foldl (+) 0 [1 .. 1000000]

foldl builds the expression ((((0 + 1) + 2) + 3) + ...) as a chain of a million thunks, and only evaluates it at the very end when the result is demanded. Each thunk is a heap object, so the chain costs memory proportional to the list length, and evaluating the outermost addition needs the next one, and so on. Older GHCs could overflow the stack here. Modern GHC has a default stack limit of 80% of memory, so you are more likely to see slowness and heavy memory use than a crash, and optimisation (-O) often fixes this specific case through strictness analysis. You should not rely on that.

The strict version evaluates the running total at each step:

HASKELL
import Data.List (foldl')

total' :: Integer
total' = foldl' (+) 0 [1 .. 1000000]

foldl' (note the prime) forces the accumulator to weak head normal form before moving on, so the accumulator is always a plain number, never a thunk chain. As a rule, use foldl' instead of foldl. In recent versions of the standard library foldl' is also exported from the Prelude, but importing it from Data.List works everywhere.

Lazy fold vs strict fold

foldl Builds a long chain of pending additions.
foldl' Adds as it goes. One number in memory.

Same answer, very different memory use.

1 / 2

seq: force one value

seq is the primitive tool:

HASKELL
seq :: a -> b -> b

a `seq` b evaluates a to weak head normal form, then returns b. It does not promise that a is fully evaluated, only its outermost constructor. For a number that is everything; for a list it only reveals the first cons cell.

You can write a strict sum loop by hand with it:

HASKELL
sumStrict :: [Int] -> Int
sumStrict = go 0
  where
    go acc []       = acc
    go acc (x : xs) =
      let acc' = acc + x
      in  acc' `seq` go acc' xs

The seq makes sure acc' is a number before the next iteration, so no thunks pile up. The related operator $! applies a function after forcing its argument: f $! x equals x `seq` f x.

Bang patterns

Writing seq everywhere is noisy. With the BangPatterns extension (enabled by default in the GHC2021 language, and available with a pragma otherwise), you put ! in front of a pattern to force that argument when the function is called:

HASKELL
# LANGUAGE BangPatterns #

mean :: [Double] -> Double
mean = go 0 0
  where
    go !s !n []       = s / fromIntegral (n :: Int)
    go !s !n (x : xs) = go (s + x) (n + 1) xs

Both accumulators are forced on every call, so the loop runs in constant space. Bang patterns also work in let and where bindings and in lambda arguments:

HASKELL
let !result = expensiveComputation input
in  use result

Here the let is evaluated immediately instead of when result is first used. This is helpful for timing, for failing early on bad input and for preventing leaks.

A bang forces to weak head normal form only. A bang on a list forces the first cell, not the elements, and a bang on a tuple does not force its components.

Strict fields in data types

Data fields are lazy by default, so a record can hold thunks for a long time. Mark a field strict with !:

HASKELL
data Stats = Stats
  { count :: !Int
  , total :: !Double
  }

Constructing a Stats now evaluates both fields to WHNF, so repeated updates in a loop do not accumulate thunks inside the record. This is cheap insurance for data that is updated many times (see Records, newtype and Type Synonyms). The language extension StrictData makes all fields in a module strict, and Strict goes further and makes bindings strict too. Both change the meaning of programs (infinite structures and knot-tying stop working), so use them deliberately.

deepseq: force everything

seq only reaches the outer layer. To evaluate a structure completely, use the deepseq package (it ships with GHC):

HASKELL
import Control.DeepSeq (force, deepseq, NFData)

main :: IO ()
main = do
  let xs = map (* 2) [1 .. 100000] :: [Int]
  xs `deepseq` putStrLn "list fully evaluated"
  print (sum (force xs))

deepseq a b evaluates a to normal form (every nested part) and returns b. force x is x `deepseq` x. Types need an NFData instance, which you can usually derive via Generic. Deep evaluation walks the entire structure, so it costs time proportional to the size of the data. Use it where you really need it, such as before timing a benchmark or when handing data to another thread, not on every function.

Do not force everything

Strictness is not always better. Forcing too early can:

  • evaluate something that would never have been needed (wasting time or failing on undefined),
  • break infinite structures such as [1 ..] or a lazily defined fibs,
  • remove the benefit of short-circuiting.

So the guideline is: keep the program lazy by default, and make accumulators and long-lived state strict. Those are exactly the places where thunk chains arise, such as counters in a loop, Map values updated with insertWith, and IORefs modified repeatedly (the library offers strict variants such as modifyIORef' and Data.Map.Strict; see Mutable State: IORef, MVar and ST).

Finding leaks

When a program uses surprising memory:

  1. Compile with -O2 and run with +RTS -s to see total allocation and maximum residency.
  2. Build with profiling and run with +RTS -hT (heap by closure type) or -h to chart the heap over time; a growing pile of thunks (THUNK) or : cells is the signature of a leak.
  3. Look for lazy accumulators: foldl, modifyIORef, lazy State counters, lazy Map values.
  4. Add strictness at those points and measure again.

More tools are in Debugging, Profiling and Performance. Guessing is a poor strategy here, because GHC's optimiser often already removes the thunks in small examples and the leaks appear only in real programs.

A stand-in: counting pending work

JavaScript is strict, so we imitate a lazy fold by building a chain of delayed additions and counting how many are left unevaluated. This is a model of the idea, not GHC's actual heap.

JS Lazy vs strict accumulation (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both give 12502500. The difference is how much unfinished work sits in memory first. For truly large inputs, evaluating a deep thunk chain would also need a very deep stack, which is the original Haskell problem.

The second stand-in imitates seq as "force a delayed value now" and shows why a strict field helps in a loop.

JS Forcing thunks: seq and strict fields (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that forcing total also evaluated the chain behind it but left count alone, just as seq only forces what you name.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main problem with foldl (+) 0 on a huge list?

    foldl delays each addition, creating a chain of thunks; foldl' forces the accumulator at every step.
  2. 2. What does a seq b do?

    seq forces its first argument to WHNF only, then the result is its second argument.
  3. 3. What does a bang pattern like go !acc (x : xs) do?

    A bang forces the matched value to WHNF, which prevents thunks building up in an accumulator.
  4. 4. Which tool evaluates a nested structure completely?

    seq stops at WHNF; deepseq and force evaluate to normal form (requires an NFData instance).
  5. 5. Where is strictness most worth adding?

    Forcing everything breaks laziness benefits; target the places where thunk chains form.

Summary

  • A space leak is memory held by unevaluated thunks, typically from lazy accumulators.
  • Prefer foldl' over foldl; it forces the accumulator at each step.
  • seq and $! force a value to weak head normal form; bang patterns (!x) do the same in patterns and let.
  • Strict fields (!Int) keep long-lived records free of thunks; StrictData applies this module-wide.
  • deepseq and force evaluate to full normal form and need NFData.
  • Stay lazy by default; add strictness where profiling (+RTS -s, heap profiles) shows leaks.

Next: Purity and Referential Transparency.