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