Hacker News new | past | comments | ask | show | jobs | submit login

A thunk is an unevaluated value. Better, it's an unevaluated piece of code that returns a value when it's required.

For instance, you can write

    x = [1..]
which gives you a list of all the positive integers. Because of laziness (which thunking enables), this line runs just fine. The compiler allocates a thunk for x, saying "okay, I know what x is now". But x is never fully evaluated (because we don't really have enough memory!): it's only evaluated as far as needed. Indeed, typing

    head x -- this is 1
makes the interpreter print the first element of the list. The rest is still in a thunk. In memory, we have something like

     [1,<unevaluated thunk>]
Now you can try doing

    head (tail x) -- this is 2
which evaluates the list only as far as the second element. Right now, in memory, the list looks something like

     [1,2,<unevaluated thunk>]
You can do similar things with basically any other datatype, enabling cool stuff like [1].

However, having to evaluate (or "force") thunks repeatedly in tight loops can obviously degrade performance: printing a Haskell list like [1..10] requires you to evaluate the first element, print it, then force the next thunk to print the 2, and so on. Comparing this to the equivalent in basically any other (strict) language, we see that a lot of indirection is removed, because the endless wrapping/unwrapping is replaced with a simple linked list of 10 elements. (I'm sure GHC is smart enough to optimize the thunking away in this toy case sufficiently.)

One might also say that a thunk is a "promise" (I'm not familiar with the JS concept of the same name, which I think is related to async things instead) to give you a certain value by calculating it only when you need it (if you do at all: a thunk stays unevaluated when you're done running the program, it's GC'd away).

[1]: http://jelv.is/blog/Lazy-Dynamic-Programming/

Thanks for the great explanations. Cheers.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact