Thunks
* A thunk is a small subroutine used for a variety of purposes like :
- Implementing call by name in Algol
- Providing a way of matching actual parameters with formal parameters ( especially useful when calling conventions are different for incomptabile modules ).
* As a side effect of the above two, thunks provide a way of lazy evaluation, ie, if you are passing some parameters (which are expressions themselves ), to functions, eager evaluation usually evaluates the whole expression/parameter list and then passes it onto the called function irrespective of whether it is used at all ( at runtime ). In case of a thunk , the first time a parameter is used, the thunk translates/evaluates the expression into an address/value at that address depending on whether the parameter is used as a lvalue/rvalue and then returns it. This evaluation takes place only once and every subsequent time, the thunk has the evaluated expression.
* This is especially useful in functional programming, where the parameters passed are functions themselves, and evaluation of functions are done only when necessary. This also helps in dealing with infinite data/ handling termination of recursive functions passed as parameters [ Call by need ]
* A thunk is implemented as a list of three items :
- Thunk Evaluator
- Expression ( denoting the actual parameter)
- Environment ( in which the thunk is evaluated ).
Once the thunk evaluates the expression in the environment, it replaces the 'Thunk Evaluator' with the value so that subsequent calls will give the value directly. In some sense, thunks are closures specifically for parameter passing.
[Reference 1]
[Reference 2]
[Reference 3]
Labels: Lazy Evaluation, Thunks
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home