Search code examples
haskelllazy-evaluationthunk

Is everything in Haskell stored in thunks, even simple values?


What do the thunks for the following value/expression/function look like in the Haskell heap?

val = 5                -- is `val` a pointer to a box containing 5?
add x y = x + y        
result = add 2 val     
main = print $ result

Would be nice to have a picture of how these are represented in Haskell, given its lazy evaluation mode.


Solution

  • Official answer

    It's none of your business. Strictly implementation detail of your compiler.

    Short answer

    Yes.

    Longer answer

    To the Haskell program itself, the answer is always yes, but the compiler can and will do things differently if it finds out that it can get away with it, for performance reasons.

    For example, for '''add x y = x + y''', a compiler might generate code that works with thunks for x and y and constructs a thunk as a result. But consider the following:

    foo :: Int -> Int -> Int
    foo x y = x * x + y * y
    

    Here, an optimizing compiler will generate code that first takes x and y out of their boxes, then does all the arithmetic, and then stores the result in a box.

    Advanced answer

    This paper describes how GHC switched from one way of implementing thunks to another that was actually both simpler and faster: http://research.microsoft.com/en-us/um/people/simonpj/papers/eval-apply/