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

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/

Leave a Comment