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