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

前端 未结 5 1622
南旧
南旧 2021-02-02 06:17

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?         


        
5条回答
  •  执念已碎
    2021-02-02 07:09

    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/

提交回复
热议问题