seq, $! and bang patterns
Weak head normal form
Forcing an expression means reducing it to weak head normal form: the outermost constructor is known and nothing inside has been forced. A list cell 1 : rest is in weak head normal form even when rest is a thunk, and a pair (a, b) is too, whatever a and b are. The distinction explains the program below: length needs the cons cells and not the elements, so a list with an error in an element still has a length.
module Main (main) where
pair :: (Int, Int)
pair = (1 + 1, error "second component")
main :: IO ()
main = do
print (length ([1, 2, 3] ++ [error "the element was not counted"] :: [Int]))
print (fst pair `seq` (5 :: Int))
putStrLn ("done " ++ show (2 :: Int))
ghc -Wall -O1 -o whnf whnf.hs
./whnf
4
5
done 2
The length is 4 because length walked four cons cells and never looked at the element that is an error. The second line is seq: it forces the pair to the outer constructor and returns 5, and the bad second component is still a thunk. This is exactly the distinction that makes a space leak possible and a strict fold necessary.
seq forces one step
seq has the type a -> b -> b and its meaning is "evaluate the first argument to weak head normal form, then return the second". It is not a function of two values in the usual sense and it does not force the fields of a constructor:
seq :: a -> b -> b
($!) :: (a -> b) -> a -> b -- f $! x = x `seq` f x
$! is the strict application, and it is the operator to reach for in a fold or an accumulator: foldl' f z xs = foldl (\acc x -> acc `seq` f acc x) z xs. The version that is already in Data.List does exactly that.
Bang patterns and $!
A bang pattern says the argument is forced when the function is entered, and it is easier to read than a chain of seq. The extension is enabled with a pragma, and a strict accumulator makes the difference between a loop and a chain of thunks:
{-# LANGUAGE BangPatterns #-}
module Main (main) where
import Control.DeepSeq (force)
import Control.Exception (ErrorCall, evaluate, try)
sumLazy :: [Int] -> Int
sumLazy = foldl (+) 0
sumStrict :: [Int] -> Int
sumStrict = go 0
where
go !acc [] = acc
go !acc (x : xs) = go (acc + x) xs
pair :: (Int, Int)
pair = (1 + 1, errorWithoutStackTrace "second component")
main :: IO ()
main = do
print (sumLazy [1 .. 10])
print (sumStrict [1 .. 10])
print (fst pair `seq` (5 :: Int))
result <- try (evaluate (force pair)) :: IO (Either ErrorCall (Int, Int))
case result of
Left err -> putStrLn ("forced: " ++ show err)
Right value -> print value
ghc -Wall -O1 -o strict strict.hs
./strict
55
55
5
forced: second component
Both sums agree, and here the lazy one is harmless because the list is ten elements long and the result is forced by the print at once. The last two lines are the point: seq on the pair was happy with the outer constructor, and force walked inside and found the error. try turned the exception into a Left, so the program did not die and the message is the one the error was given.
hlint suggests sum for foldl (+) 0 and it is right for a program whose only job is to add; the line stays here on purpose, because this lesson is about the fold and not about the sum. A reader who applies the hint loses the example.
deepseq forces everything
Control.DeepSeq has a class NFData with the method rnf, which forces a value completely, and force, which is rnf followed by the identity. Every Prelude type used here has an instance, and a data type of your own can derive one:
class NFData a where rnf :: a -> ()
force :: NFData a => a -> a
deepseq :: NFData a => a -> b -> b
The cost is a full traversal, so force belongs at the boundary of a strict data structure and not inside every function. The evaluate (force x) in the program is the usual shape: evaluate runs the action of forcing and force makes sure it goes all the way down.
When to be strict
- Accumulators in a loop: strict, with foldl', a bang pattern or $!.
- A large data structure built and then forced once: laziness is fine, and forcing inside the build only slows it down.
- A field that is never optional, such as a count in a record: a strict field with !Int keeps it evaluated.
- A lazy field that is expensive and often unused: leave it lazy on purpose and say so in a comment.
The next lesson measures the difference: the same million-element sum with foldl and foldl' under +RTS -s, with the maximum residency of each. That number is the reason this lesson exists.
Exercises
- Force a list of pairs with seq and then with force and compare the errors.
- Write mean :: [Double] -> Double with a strict pair of a sum and a count.
- Add a bang pattern to a function of your own and explain what it changes.
- Derive NFData for a small data type and force a value with a bad field.
- Replace foldl (+) 0 with foldl' in the strict program and say whether the output changes.
- Explain why seq on a pair does not force either component.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
seq a bdo?Answer
Evaluates a to weak head normal form and returns b
seq forces the first argument one step and its value is the second argument.
-
What is weak head normal form?
Answer
The outer constructor is known and the fields may still be thunks
WHNF stops at the outermost constructor, which is why a pair can be in WHNF with an error inside.
-
What does
$!do?Answer
Applies the function after forcing the argument to WHNF
f $! x is x
seqf x, the strict application. -
What does this program print?
module Main (main) where main :: IO () main = print (length ([1, 2, 3 :: Int] ++ [error "x"]))Answer
4
length counts the cons cells and never forces the element that is an error.
-
What does a bang pattern do?
Answer
Forces the argument when the function is entered
The pattern
!xevaluates x to WHNF before the body runs. -
What does
forcefrom deepseq do?Answer
Forces the whole value, including every field
force is rnf followed by the identity, so the value is fully evaluated.
-
What does this program print?
module Main (main) where main :: IO () main = print (foldl (+) 0 [1, 2, 3 :: Int])Answer
6
The fold adds the three numbers and the result is 6.
-
Why did
fst pairseq5return 5 even though the second component is an error?Answer
seq forces the pair to the outer constructor and not the components
The pair reached WHNF, and WHNF does not look inside the fields.
-
When is
forcea bad idea?Answer
Inside a function that builds a large structure which is only partly used
Forcing a structure that a caller uses partially throws away the benefit of laziness.
-
What does
evaluate (force x)guarantee?Answer
The action forces x completely and may throw its exception in IO
evaluate runs the forcing as an IO action, so an exception inside x appears where the action is run.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev