[Haskell-cafe] Stack, Heap and GHC

David House dmhouse at gmail.com
Fri Dec 15 17:46:17 EST 2006


On 15/12/06, Felix Breuer <felix at fbreuer.de> wrote:
> 1) What precisely is a thunk?

It's a memory cell that says 'I'm an unevaluated value, to evaluate me
do X'. For example, consider the differences between the following
programs:

(common for all that follows)
myFunc :: [Int] -> [Int]

(1) myFunc xs = ...
(2) myFunc (x:xs) = ...
(3) myFunc (5:x:[]) = ...

(Assume all the pattern matches are successful.) In the RHS of (1), xs
refers to a thunk that is the unevaluated list. In (2), you evaluate
the first level (to weak head normal form, or whnf) of the list to
reveal a cons cell, where the head and tail are both thunks (and can
be accessed by x and xs respectively). In (3), you evaluate the first
level of the list, revealing a cons cell. You then evaluate the head
of this cell, revealing a 5 (so no thunks here; everything's fully
evaluated). The tail gets evaluated to a further cons cell where the
head is an unevaluated thunk and the tail is evaluated to the empty
list (so again, no thunks).

Hopefully that gives you some kind of intuition regarding thunks and
the implementation of laziness in Haskell.

-- 
-David House, dmhouse at gmail.com


More information about the Haskell-Cafe mailing list