Closures/Value capture: Difference between revisions

Content deleted Content added
added c++
Line 187: Line 187:
writeln(map!q{ a() }(funcs));
writeln(map!q{ a() }(funcs));
}</lang>
}</lang>

=={{header|Factor}}==
<lang factor>USING: io kernel locals math math.ranges prettyprint sequences ;

! Create a sequence of ten quotations
[let
10 iota [
:> i ! Bind lexical variable i
[ i i * ] ! Push a quotation to calculate i squared
] map :> seq

{ 3 8 } [
dup pprint " squared is " write
seq nth call .
] each
]</lang>

<pre>$ ./factor script.factor
3 squared is 9
8 squared is 64</pre>

The code <code>:> i</code> always binds a new variable. This happens inside a loop, so this program creates 10 different bindings. Each closure <code>[ i i * ]</code> captures a different binding, and remembers a different value.

The wrong way would use <code>f :> i! 10 iota [ i! [ i i * ] ] map :> seq</code> to mutate a single binding. Then the program would print, "3 squared is 81", "8 squared is 81".


=={{header|Fantom}}==
=={{header|Fantom}}==