Haskell Thunks
A thunk is an unevaluated promise for a value in Haskell. It holds the work needed to compute the value until that value is forced.
An unused thunk does no work
The program defines a large sum but never uses it. Only the small result is printed.
main :: IO ()
main = let big = sum ([1..1000] :: [Int]) in print (1 + 1)Forcing a thunk gives its value
The product is a thunk until print asks for it. Printing it gives 12.
main :: IO ()
main = let x = 3 * 4 in print xA shared thunk gives the same result twice
The same thunk is added to itself. Both uses see the value 10, so the total is 20.
main :: IO ()
main = let y = 2 * 5 in print (y + y)Example
main :: IO ()
main = do
let base = 4 * 5
let doubled = base * 2
print base
print doubledKey points
- Promise: a thunk stores work, not a finished result.
- Forcing: using a thunk's value in a print or a test computes it.
- Sharing: the same thunk used twice gives the same result both times.
- Unused thunk: a thunk that is never used is never computed.
- Expression: a binding like let x = 1 + 2 creates a thunk for x.
In this example, base is a thunk for 20. Doubled is built from base and is a thunk for 40. The two prints force each thunk in turn.
Note
a thunk is invisible in ordinary code, so its name is the only sign of it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is a thunk?