Closures/Value capture: Difference between revisions

Content deleted Content added
m →‎{{header|Factor}}: Move a comment.
→‎{{header|Factor}}: "Forget the variable!" Add a version that uses fried quotations.
Line 189: Line 189:


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


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


Line 211: Line 212:


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".
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".

===Using fried quotations===
Forget the variable! Each ''fried quotation'' captures some values by pulling them from the stack.

<lang factor>USING: fry io kernel math prettyprint sequences ;

! Push a sequence of 10 quotations
10 iota [
'[ _ dup * ] ! Push a quotation ( i -- i*i )
] map

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


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