programming-languagesfunctional-programmingscheme

What is a 'thunk', as used in Scheme or in general?


I come across the word 'thunk' at a lot of places in code and documentation related to Scheme, and similar territories. I am guessing that it is a generic name for a procedure, which has a single formal argument. Is that correct? If yes, is there more to it? If no, please?

For eg. in SRFI 18, in the 'Procedures' section.


Solution

  • It is really simple. When you have some computation, like adding 3 to 5, in your program, then creating a thunk of it means not to calculate it directly, but instead create a function with zero arguments that will calculate it when the actual value is needed.

    (let ((foo (+ 3 5))) ; the calculation is performed directly, foo is 8
      ;; some other things
      (display foo)) ; foo is evaluated to 8 and printed
    
    (let ((foo (lambda () (+ 3 5)))) ; the calculation is delayed, foo is a
                                     ; function that will perform it when needed
      ;; some other things
      (display (foo))) ; foo is evaluated as a function, returns 8 which is printed
    

    In the second case, foo would be called a thunk.

    Lazy languages blur the line between binding a variable to a value and creating a function to return that value, so that writing something like the first form above is actually treated like the second, under the hood.