TExcelTAD
Home › Haskell › Haskell Laziness & Infinite Lists

Haskell Laziness & Infinite Lists

Haskell evaluates expressions lazily: a value is computed only when something actually needs it, and then at most once. Most languages are strict (eager): arguments are evaluated before a function is called. Laziness lets you separate what to compute from how much of it to compute.

Nothing happens until it is needed

haskell · try it yourself
expensive :: Int
expensive = sum [1 .. 10000000]

pick :: Bool -> Int -> Int -> Int
pick useFirst a b = if useFirst then a else b

main :: IO ()
main = do
  print (pick False expensive 42)          -- expensive is never computed
  print (fst (1, error "never evaluated"))  -- error is never touched
  print (length [undefined, undefined])     -- length doesn't look at elements
  let xs = [1, 2, 3, error "boom"]
  print (take 3 xs)
42
1
2
[1,2,3]

error "…" and undefined crash the program when evaluated. Here they are never evaluated, so the program runs fine. In a strict language each of these lines would fail.

Infinite lists

Because elements are computed on demand, a list can be infinite as long as you only consume a finite part of it:

haskell · try it yourself
main :: IO ()
main = do
  let naturals = [0 ..]
      evens = filter even naturals
      powersOfTwo = iterate (* 2) 1
      cycleDays = cycle ["Mon", "Tue", "Wed"]
  print (take 5 evens)
  print (takeWhile (< 1000) powersOfTwo)
  print (take 7 cycleDays)
  print (take 4 (repeat 'z'))
  print (head (dropWhile (< 500) (map (^ 2) naturals)))
  print (zip "abc" [1 ..])                 -- number the elements of a finite list
[0,2,4,6,8]
[1,2,4,8,16,32,64,128,256,512]
["Mon","Tue","Wed","Mon","Tue","Wed","Mon"]
"zzzz"
529
[('a',1),('b',2),('c',3)]
Generator Produces
[n ..] n, n+1, n+2, …
iterate f x x, f x, f (f x), …
repeat x x, x, x, …
cycle xs xs ++ xs ++ xs ++ …

zip "abc" [1 ..] shows an everyday idiom: pair a finite list with an infinite counter, and zip stops when the shorter one runs out.

Defining lists in terms of themselves

A lazy list can refer to itself, as long as each element only depends on earlier ones. This gives the famous one-line Fibonacci sequence, which runs in linear time (unlike the naive recursive version):

haskell · try it yourself
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

primes :: [Int]
primes = sieve [2 ..]
  where
    sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
    sieve [] = []

main :: IO ()
main = do
  print (take 15 fibs)
  print (fibs !! 100)
  print (take 12 primes)
  print (takeWhile (< 60) primes)
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]
354224848179261915075
[2,3,5,7,11,13,17,19,23,29,31,37]
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59]

How does fibs work? Line the list up with its own tail and add:

text
fibs        = 0 : 1 : 1 : 2 : 3 : 5 : ...
tail fibs   = 1 : 1 : 2 : 3 : 5 : ...
zipWith (+) = 1 : 2 : 3 : 5 : 8 : ...   -- which is fibs from the third element on

(The sieve is elegant but not the real Sieve of Eratosthenes, and it gets slow for big primes. It's a demonstration of laziness, not an efficient algorithm.)

Separating generation from selection

Laziness lets you write a "produce all candidates" function and a separate "pick the ones I want" function, without paying for candidates you never look at:

haskell · try it yourself
collatz :: Int -> [Int]
collatz = takeWhile (/= 1) . iterate step
  where
    step n = if even n then n `div` 2 else 3 * n + 1

-- the first square number whose digits add up to 31
digitSum :: Int -> Int
digitSum = sum . map (read . pure) . show

main :: IO ()
main = do
  print (collatz 6 ++ [1])
  print (length (collatz 27))
  print (head [n * n | n <- [1 ..], digitSum (n * n) == 31])
[6,3,10,5,16,8,4,2,1]
111
6889

[n * n | n <- [1 ..], …] is an infinite list of matches; head stops the search at the first one.

Thunks: the cost of laziness

An unevaluated expression is stored as a thunk, a small heap object that remembers "how to compute this". Once forced, the thunk is overwritten with its value, so it is never computed twice:

haskell · try it yourself
import Debug.Trace (trace)

main :: IO ()
main = do
  let x = trace "computing x" (21 * 2)
  putStrLn "before"
  print (x + x)          -- x is evaluated once, then shared
  print x
before
84
42
computing x

trace (from Debug.Trace) prints a message to standard error when its value is forced, which makes evaluation order visible. In a terminal you would see "computing x" between "before" and 84: the definition did nothing, and the first use forced it. Either way it appears only once, although x is used three times.

Thunks are usually cheap, but a long chain of unevaluated thunks can use a lot of memory, for example when summing a huge list with a lazy accumulator. The next lesson, Strictness, shows how to avoid that.

Note: In the playground, standard error is shown after all of standard output, which is why the trace message is the last line above. Use trace only for debugging; it breaks purity on purpose.

Test yourself

Why does fst (5, undefined) return 5 without crashing?

  1. undefined is a valid number
  2. Laziness: the second component is never evaluated
  3. GHC removes undefined
  4. It crashes

What is take 5 (cycle [1, 2])?

  1. [1,2]
  2. [1,2,1,2,1]
  3. [1,1,1,1,1]
  4. It loops forever

What is a thunk?

  1. A compiled function
  2. An unevaluated expression stored until its value is needed
  3. A type class
  4. A kind of exception