| 1 |
= Closure |
| 2 |
|
| 3 |
A closure is a data structure that is the run-time representation of a |
| 4 |
function. |
| 5 |
|
| 6 |
|
| 7 |
== Typical Implementation |
| 8 |
|
| 9 |
In a typical implementation, a closure consists of a _code pointer_ |
| 10 |
(indicating what the function does) and an _environment_ containing |
| 11 |
the values of the free variables of the function. For example, in the |
| 12 |
expression |
| 13 |
|
| 14 |
[source,sml] |
| 15 |
---- |
| 16 |
let |
| 17 |
val x = 5 |
| 18 |
in |
| 19 |
fn y => x + y |
| 20 |
end |
| 21 |
---- |
| 22 |
|
| 23 |
the closure for `fn y \=> x + y` contains a pointer to a piece of code |
| 24 |
that knows to take its argument and add the value of `x` to it, plus |
| 25 |
the environment recording the value of `x` as `5`. |
| 26 |
|
| 27 |
To call a function, the code pointer is extracted and jumped to, |
| 28 |
passing in some agreed upon location the environment and the argument. |
| 29 |
|
| 30 |
|
| 31 |
== MLton's Implementation |
| 32 |
|
| 33 |
MLton does not implement closures traditionally. Instead, based on |
| 34 |
whole-program higher-order control-flow analysis, MLton represents a |
| 35 |
function as an element of a sum type, where the variant indicates |
| 36 |
which function it is and carries the free variables as arguments. See |
| 37 |
<<ClosureConvert#>> and <<References#CejtinEtAl00,CejtinEtAl00>> for details. |