Closures/Value capture: Difference between revisions
(→{{header|TXR}}: Adding.) |
|||
(110 intermediate revisions by 48 users not shown) | |||
Line 1: | Line 1: | ||
[[Category:Functions and subroutines]] |
|||
{{task}} |
{{task}} |
||
'''Task:''' Create a list of 10 functions, in the simplest manner possible |
|||
(anonymous functions are encouraged), such that the function at index <math>i</math> |
|||
(you may choose to start <math>i</math> from either 0 or 1), when run, |
|||
should return the square of the index, that is, <math>i^2</math>. |
|||
Display the result of running any but the last function, |
|||
to demonstrate that the function indeed remembers its value. |
|||
;Task: |
|||
'''Goal:''' To demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. |
|||
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index <big> ''<b> i </b>'' </big> (you may choose to start <big> ''<b> i </b>'' </big> from either <big> '''0''' </big> or <big> '''1'''), </big> when run, should return the square of the index, that is, <big> ''<b> i </b>'' <sup>2</sup>.</big> |
|||
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. |
|||
;Goal: |
|||
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. |
|||
In imperative languages, one would generally use a loop with a mutable counter variable. |
In imperative languages, one would generally use a loop with a mutable counter variable. |
||
For each function to maintain the correct number, it has to capture the ''value'' |
|||
of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. |
For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. |
||
See also: [[Multiple distinct objects]] |
|||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">[(() -> Int)] funcs |
|||
L(i) 10 |
|||
funcs.append(() -> @=i * @=i) |
|||
print(funcs[3]())</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
9 |
|||
</pre> |
|||
=={{header|Acornsoft Lisp}}== |
|||
Since this Lisp is dynamically scoped and does not have any built-in closure mechanism, we have to construct one which we'll call <code>freeze</code>. (The name is inspired by the [[Pop-2]] programming languages's "frozen formals".) |
|||
('''freeze''' ''varlist lambda-expr'') finds the current values of the variables in ''varlist'' and returns a lambda-expression that is like the original except that, when called, it binds those variables to their captured values. For example, if <code>a</code>'s value is 1 and <code>b</code>'s is 2, |
|||
<syntaxhighlight lang="lisp"> |
|||
(freeze '(a b) '(lambda (c) (list a b c))) |
|||
</syntaxhighlight> |
|||
would return |
|||
<syntaxhighlight lang="lisp"> |
|||
(lambda (c) |
|||
((lambda ((a . 1) (b . 2)) |
|||
(list a b c)))) |
|||
</syntaxhighlight> |
|||
What does that mean? A cons (''name'' . ''value'') in a lambda-expressions's formal parameters is the syntax for a formal with a default value. The ''value'' is literally the value; it's not an expression that's evaluated. This |
|||
<syntaxhighlight lang="lisp"> |
|||
( (lambda ((a . 1) (b . 2)) |
|||
(list a b c)) ) |
|||
</syntaxhighlight> |
|||
calls the function represented by that lambda-expression. Since it does not give the function any arguments, <code>a</code> and <code>b</code> get their default values (which are the values captured by <code>freeze</code>). |
|||
(Although code within such a 'closure' can assign new values to the captured variables, it would have only a temporary effect and would not change the values seen in subsequent calls to the same closure. That's one sense in which the variable values are "frozen".) |
|||
Here is the definition of <code>freeze</code>: |
|||
<syntaxhighlight lang="lisp"> |
|||
(defun freeze (_fvars_ _lambda-expr_) |
|||
(freeze-vars |
|||
(mapc cons _fvars_ (mapc eval _fvars_)) |
|||
(cadr _lambda-expr_) |
|||
(cddr _lambda-expr_))) |
|||
(defun freeze-vars (bindings lvars lbody) |
|||
(list 'lambda lvars |
|||
(list (cons 'lambda (cons bindings lbody))))) |
|||
</syntaxhighlight> |
|||
Once we have <code>freeze</code>, we can create a list of square-returning functions and then call them: |
|||
<syntaxhighlight lang="lisp"> |
|||
(defun range (from to) |
|||
(cond ((greaterp from to) '()) |
|||
(t (cons from (range (add1 from) to))))) |
|||
(defun example () |
|||
(mapc '(lambda (f) (f)) |
|||
(mapc '(lambda (i) |
|||
(freeze '(i) '(lambda () (times i i)))) |
|||
(range 1 10)))) |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<code>(example)</code> returns |
|||
<pre>(1 4 9 16 25 36 49 64 81 100)</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Line 16: | Line 93: | ||
One way to realize closures in Ada is the usage of protected objects. |
One way to realize closures in Ada is the usage of protected objects. |
||
< |
<syntaxhighlight lang="Ada">with Ada.Text_IO; |
||
procedure Value_Capture is |
procedure Value_Capture is |
||
Line 45: | Line 122: | ||
Ada.Text_IO.Put(Integer'Image(A(I).Result)); |
Ada.Text_IO.Put(Integer'Image(A(I).Result)); |
||
end loop; |
end loop; |
||
end Value_Capture;</ |
end Value_Capture;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 4 9 16 25 36 49 64 81</pre> |
<pre> 1 4 9 16 25 36 49 64 81</pre> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G|2.8}} |
{{works with|ALGOL 68G|2.8}} |
||
< |
<syntaxhighlight lang="algol68"> |
||
[1:10]PROC(BOOL)INT squares; |
[1:10]PROC(BOOL)INT squares; |
||
Line 67: | Line 142: | ||
FOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD |
FOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 75: | Line 150: | ||
Using partial parametrization as proposed in Algol Bulletin by Charles Lindsey. Algol68G does not support binding ''all'' actual parameters "partially" without deproceduring, so a PROC(BOOL)INT mode is used instead of a PROC INT. The variable ''captured i'' is passed twice, once by reference and once by value, to demonstrate that it is possible to capture both ways, and a little extra code is added to show that the closure can modify the captured variable. |
Using partial parametrization as proposed in Algol Bulletin by Charles Lindsey. Algol68G does not support binding ''all'' actual parameters "partially" without deproceduring, so a PROC(BOOL)INT mode is used instead of a PROC INT. The variable ''captured i'' is passed twice, once by reference and once by value, to demonstrate that it is possible to capture both ways, and a little extra code is added to show that the closure can modify the captured variable. |
||
=={{header|AntLang}}== |
|||
<syntaxhighlight lang="AntLang">fns: {n: x; {n expt 2}} map range[10] |
|||
(8 elem fns)[]</syntaxhighlight> |
|||
=={{header|AppleScript}}== |
|||
{{trans|JavaScript}} |
|||
<syntaxhighlight lang="AppleScript">on run |
|||
set fns to {} |
|||
repeat with i from 1 to 10 |
|||
set end of fns to closure(i) |
|||
end repeat |
|||
|λ|() of item 3 of fns |
|||
end run |
|||
on closure(x) |
|||
script |
|||
on |λ|() |
|||
x * x |
|||
end |λ| |
|||
end script |
|||
end closure</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>9</pre> |
|||
Or, in a more functional pattern of composition: |
|||
<syntaxhighlight lang="AppleScript">-- CLOSURE -------------------------------------------------------------------- |
|||
script closure |
|||
on |λ|(x) |
|||
script |
|||
on |λ|() |
|||
x * x |
|||
end |λ| |
|||
end script |
|||
end |λ| |
|||
end script |
|||
|λ|() of (item 3 of (map(closure, enumFromTo(1, 10)))) |
|||
-- GENERIC FUNCTIONS ---------------------------------------------------------- |
|||
-- enumFromTo :: Int -> Int -> [Int] |
|||
on enumFromTo(m, n) |
|||
if n < m then |
|||
set d to -1 |
|||
else |
|||
set d to 1 |
|||
end if |
|||
set lst to {} |
|||
repeat with i from m to n by d |
|||
set end of lst to i |
|||
end repeat |
|||
return lst |
|||
end enumFromTo |
|||
-- map :: (a -> b) -> [a] -> [b] |
|||
on map(f, xs) |
|||
tell mReturn(f) |
|||
set lng to length of xs |
|||
set lst to {} |
|||
repeat with i from 1 to lng |
|||
set end of lst to |λ|(item i of xs, i, xs) |
|||
end repeat |
|||
return lst |
|||
end tell |
|||
end map |
|||
-- Lift 2nd class handler function into 1st class script wrapper |
|||
-- mReturn :: Handler -> Script |
|||
on mReturn(f) |
|||
if class of f is script then |
|||
f |
|||
else |
|||
script |
|||
property |λ| : f |
|||
end script |
|||
end if |
|||
end mReturn</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>9</pre> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="arturo">funcs: [ø] |
|||
loop 1..10 'f -> |
|||
'funcs ++ function [] with 'f [ |
|||
f * f |
|||
] |
|||
print call funcs\3 []</syntaxhighlight> |
|||
{{out}} |
|||
<pre>9</pre> |
|||
=={{header|Axiom}}== |
=={{header|Axiom}}== |
||
Using the Spad compiler: |
Using the Spad compiler: |
||
< |
<syntaxhighlight lang="Axiom">)abbrev package TESTP TestPackage |
||
TestPackage() : with |
TestPackage() : with |
||
test: () -> List((()->Integer)) |
test: () -> List((()->Integer)) |
||
== add |
== add |
||
test() == [(() +-> i^2) for i in 1..10]</ |
test() == [(() +-> i^2) for i in 1..10]</syntaxhighlight> |
||
This can be called from the interpreter using: |
This can be called from the interpreter using: |
||
< |
<syntaxhighlight lang="Axiom">[x() for x in test()]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="Axiom">[1,4,9,16,25,36,49,64,81,100] |
||
Type: List(Integer)</ |
Type: List(Integer)</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang="babel">((main { |
||
{ iter |
{ iter |
||
1 take bons 1 take |
1 take bons 1 take |
||
Line 102: | Line 273: | ||
10 times |
10 times |
||
collect ! |
collect ! |
||
{eval %d nl <<} each }))</ |
{eval %d nl <<} each }))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="babel">100 |
||
81 |
81 |
||
64 |
64 |
||
Line 114: | Line 285: | ||
9 |
9 |
||
4 |
4 |
||
1</ |
1</syntaxhighlight> |
||
Essentially, a function has been constructed for each value to be squared (10 down to 1). The cp operator ensures that we generate a fresh copy of the number to be squared, as well as the code for multiplying, {*}. |
Essentially, a function has been constructed for each value to be squared (10 down to 1). The cp operator ensures that we generate a fresh copy of the number to be squared, as well as the code for multiplying, {*}. |
||
In the final each loop, we eval each of the constructed functions and output the result. |
In the final each loop, we eval each of the constructed functions and output the result. |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( -1:?i |
||
& :?funcs |
& :?funcs |
||
& whl |
& whl |
||
Line 128: | Line 298: | ||
& whl'(!funcs:%?func %?funcs&out$(!func$)) |
& whl'(!funcs:%?func %?funcs&out$(!func$)) |
||
); |
); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>0 |
<pre>0 |
||
Line 139: | Line 309: | ||
49 |
49 |
||
64</pre> |
64</pre> |
||
=={{header|C}}== |
=={{header|C}}== |
||
Line 146: | Line 315: | ||
Non-portable. Copying a function body depends on implementation-specific semantics of volatile, if the replacement target still exists after optimization, if the dest memory is suitably aligned, if the memory is executable, if it makes any function calls to a relative offset, if it refers to any memory location with an absolute address, etc. It only very occasionally works. |
Non-portable. Copying a function body depends on implementation-specific semantics of volatile, if the replacement target still exists after optimization, if the dest memory is suitably aligned, if the memory is executable, if it makes any function calls to a relative offset, if it refers to any memory location with an absolute address, etc. It only very occasionally works. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <string.h> |
#include <string.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 186: | Line 355: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<lang>func[0]: 0 |
<syntaxhighlight lang="text">func[0]: 0 |
||
func[1]: 1 |
func[1]: 1 |
||
func[2]: 4 |
func[2]: 4 |
||
Line 196: | Line 365: | ||
func[6]: 36 |
func[6]: 36 |
||
func[7]: 49 |
func[7]: 49 |
||
func[8]: 64</ |
func[8]: 64</syntaxhighlight> |
||
===Greenspunned mini Lisp dialect=== |
===Greenspunned mini Lisp dialect=== |
||
Line 202: | Line 371: | ||
See [[Closures/Variable_capture/C]] for complete code. The relevant excerpt is: |
See [[Closures/Variable_capture/C]] for complete code. The relevant excerpt is: |
||
< |
<syntaxhighlight lang="c">void init(void) |
||
{ |
{ |
||
t = intern(lit("t")); |
t = intern(lit("t")); |
||
Line 234: | Line 403: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Here, we create an environment explicitly as an association list |
Here, we create an environment explicitly as an association list |
||
Line 254: | Line 423: | ||
0 |
0 |
||
</pre> |
</pre> |
||
=={{header|C++}}== |
|||
{{works with|C++11}} |
|||
<lang cpp>#include <iostream> |
|||
#include <functional> |
|||
#include <vector> |
|||
int main() { |
|||
std::vector<std::function<int()> > funcs; |
|||
for (int i = 0; i < 10; i++) |
|||
funcs.push_back([=]() { return i * i; }); |
|||
for ( std::function<int( )> f : funcs ) |
|||
std::cout << f( ) << std::endl ; |
|||
return 0; |
|||
}</lang> |
|||
{{out}} |
|||
<pre>0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
===Using Linq=== |
===Using Linq=== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 298: | Line 439: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<lang>0 |
<syntaxhighlight lang="text">0 |
||
1 |
1 |
||
4 |
4 |
||
Line 308: | Line 449: | ||
36 |
36 |
||
49 |
49 |
||
64</ |
64</syntaxhighlight> |
||
===Using delegates only=== |
===Using delegates only=== |
||
< |
<syntaxhighlight lang="csharp"> |
||
using System; |
using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 335: | Line 476: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<lang>0 |
<syntaxhighlight lang="text">0 |
||
1 |
1 |
||
4 |
4 |
||
Line 345: | Line 486: | ||
36 |
36 |
||
49 |
49 |
||
64</ |
64</syntaxhighlight> |
||
=={{header|C++}}== |
|||
{{works with|C++11}} |
|||
<syntaxhighlight lang="cpp">#include <iostream> |
|||
#include <functional> |
|||
#include <vector> |
|||
int main() { |
|||
std::vector<std::function<int()> > funcs; |
|||
for (int i = 0; i < 10; i++) |
|||
funcs.push_back([=]() { return i * i; }); |
|||
for ( std::function<int( )> f : funcs ) |
|||
std::cout << f( ) << std::endl ; |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
|||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void run() { |
||
//create a list of closures with a list comprehension |
//create a list of closures with a list comprehension |
||
Line 356: | Line 522: | ||
print("closure number ``i`` returns: ``closure()``"); |
print("closure number ``i`` returns: ``closure()``"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
|||
<syntaxhighlight lang="clojure">(def funcs (map #(fn [] (* % %)) (range 11))) |
|||
(printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>9 |
|||
16</pre> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
# Generate an array of functions. |
# Generate an array of functions. |
||
funcs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i ) |
funcs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i ) |
||
Line 366: | Line 537: | ||
# Call each function to demonstrate value capture. |
# Call each function to demonstrate value capture. |
||
console.log func() for func in funcs |
console.log func() for func in funcs |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">CL-USER> (defparameter alist |
||
(loop for i from 1 to 10 |
(loop for i from 1 to 10 |
||
collect (cons i (let ((i i)) |
collect (cons i (let ((i i)) |
||
Line 377: | Line 547: | ||
4 |
4 |
||
CL-USER> (funcall (cdr (assoc 8 alist))) |
CL-USER> (funcall (cdr (assoc 8 alist))) |
||
64</ |
64</syntaxhighlight> |
||
The ''loop'' mutates its binding ''i''. The purpose of <code>(let ((i i)) ...)</code> is to create a different binding ''i'' for each ''lambda'' to capture. Otherwise, all 10 lambdas would capture the same binding and return 100. |
The ''loop'' mutates its binding ''i''. The purpose of <code>(let ((i i)) ...)</code> is to create a different binding ''i'' for each ''lambda'' to capture. Otherwise, all 10 lambdas would capture the same binding and return 100. |
||
=={{header|D}}== |
=={{header|D}}== |
||
===Less Functional Version=== |
===Less Functional Version=== |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
void main() { |
void main() { |
||
Line 392: | Line 561: | ||
writeln(funcs[3]()); |
writeln(funcs[3]()); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>9</pre> |
<pre>9</pre> |
||
===More Functional Version=== |
===More Functional Version=== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.range, std.algorithm; |
import std.stdio, std.range, std.algorithm; |
||
10.iota.map!(i => () => i ^^ 2).map!q{ a() }.writeln; |
10.iota.map!(i => () => i ^^ 2).map!q{ a() }.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</pre> |
<pre>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</pre> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{works with|Delphi 2009}} |
{{works with|Delphi 2009}} |
||
< |
<syntaxhighlight lang="Delphi">program Project1; |
||
type |
type |
||
Line 432: | Line 600: | ||
for i := Low(Funcs) to High(Funcs) do |
for i := Low(Funcs) to High(Funcs) do |
||
Writeln(Funcs[i]()); |
Writeln(Funcs[i]()); |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0 |
<pre>0 |
||
Line 445: | Line 613: | ||
81 |
81 |
||
</pre> |
</pre> |
||
=={{header|Dyalect}}== |
|||
Dyalect captures variables by reference, therefore a way to achieve this is to capture a variable through a closure which in its turn returns a anonymous function like so: |
|||
<syntaxhighlight lang="dyalect">var xs = [] |
|||
let num = 10 |
|||
for n in 0..<num { |
|||
xs.Add((n => () => n * n)(n)) |
|||
} |
|||
for x in xs { |
|||
print(x()) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81</pre> |
|||
This is similar to a JavaScript (ES6) solution. |
|||
=={{header|EchoLisp}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
(define (fgen i) (lambda () (* i i))) |
|||
(define fs (for/vector ((i 10)) (fgen i))) ;; vector of 10 anonymous functions |
|||
((vector-ref fs 5)) ;; calls fs[5] |
|||
→ 25 |
|||
</syntaxhighlight> |
|||
=={{header|Elena}}== |
|||
ELENA 6.x : |
|||
<syntaxhighlight lang="elena">import system'routines; |
|||
import extensions; |
|||
public program() |
|||
{ |
|||
var functions := Array.allocate(10).populate::(int i => { ^ i * i} ); |
|||
functions.forEach::(func) { console.printLine(func()) } |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81</pre> |
|||
=={{header|Elixir}}== |
|||
<syntaxhighlight lang="elixir">funs = for i <- 0..9, do: (fn -> i*i end) |
|||
Enum.each(funs, &IO.puts &1.())</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
As of Emacs 24.3, lexical closures are supported, therefore alleviating hacks such as lexical-let. |
|||
Emacs Lisp now has lexical-let, which allows for the capture of variables. |
|||
<lang lisp> |
|||
(require 'cl) |
|||
(mapcar 'funcall |
|||
(mapcar (lambda (x) |
|||
(lexical-let ((x x)) |
|||
(lambda () (* x x)))) [1 2 3 4 5 6 7 8 9 10])) |
|||
;; => (1 4 9 16 25 36 49 64 81 100) |
|||
</lang> |
|||
<syntaxhighlight lang="lisp">;; -*- lexical-binding: t; -*- |
|||
(mapcar #'funcall |
|||
(mapcar (lambda (x) |
|||
(lambda () |
|||
(* x x))) |
|||
'(1 2 3 4 5 6 7 8 9 10))) |
|||
;; => (1 4 9 16 25 36 49 64 81 100)</syntaxhighlight> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Erlang uses lexical scoping and has anonymous functions. |
Erlang uses lexical scoping and has anonymous functions. |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(capture_demo). |
-module(capture_demo). |
||
-export([demo/0]). |
-export([demo/0]). |
||
Line 473: | Line 714: | ||
io:fwrite("~B~n",[F()]) |
io:fwrite("~B~n",[F()]) |
||
end, Funs). |
end, Funs). |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
1> capture_demo:demo(). |
1> capture_demo:demo(). |
||
Line 488: | Line 729: | ||
ok |
ok |
||
</pre> |
</pre> |
||
=={{header|F_Sharp|F#}}== |
|||
Nearly identical to OCaml |
|||
<syntaxhighlight lang="fsharp">[<EntryPoint>] |
|||
let main argv = |
|||
let fs = List.init 10 (fun i -> fun () -> i*i) |
|||
do List.iter (fun f -> printfn "%d" <| f()) fs |
|||
0</syntaxhighlight> |
|||
With List.map |
|||
<syntaxhighlight lang="fsharp">[<EntryPoint>] |
|||
let main argv = |
|||
let fs = List.map (fun i -> fun () -> i*i) [0..9] |
|||
do List.iter (fun f -> printfn "%d" <| f()) fs |
|||
0</syntaxhighlight> |
|||
With List.mapi |
|||
<syntaxhighlight lang="fsharp">[<EntryPoint>] |
|||
let main argv = |
|||
let fs = List.mapi (fun i x -> fun () -> i*i) (List.replicate 10 None) |
|||
do List.iter (fun f -> printfn "%d" <| f()) fs |
|||
0</syntaxhighlight> |
|||
With an infinite sequence |
|||
<syntaxhighlight lang="fsharp">[<EntryPoint>] |
|||
let main argv = |
|||
let fs = Seq.initInfinite (fun i -> fun () -> i*i) |
|||
do Seq.iter (fun f -> printfn "%d" <| f()) (Seq.take 10 fs) |
|||
0</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
===Using lexical variables=== |
===Using lexical variables=== |
||
< |
<syntaxhighlight lang="factor">USING: io kernel locals math prettyprint sequences ; |
||
[let |
[let |
||
Line 504: | Line 786: | ||
seq nth call . |
seq nth call . |
||
] each |
] each |
||
]</ |
]</syntaxhighlight> |
||
<pre>$ ./factor script.factor |
<pre>$ ./factor script.factor |
||
Line 517: | Line 799: | ||
Forget the variable! Each ''fried quotation'' captures some values by pulling them from the stack. |
Forget the variable! Each ''fried quotation'' captures some values by pulling them from the stack. |
||
< |
<syntaxhighlight lang="factor">USING: fry io kernel math prettyprint sequences ; |
||
! Push a sequence of 10 quotations |
! Push a sequence of 10 quotations |
||
Line 528: | Line 810: | ||
over nth call . |
over nth call . |
||
] each |
] each |
||
drop</ |
drop</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Closures |
class Closures |
||
{ |
{ |
||
Line 550: | Line 831: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Function at index: 7 outputs 49 |
Function at index: 7 outputs 49 |
||
</pre> |
|||
=={{header|Forth}}== |
|||
<syntaxhighlight lang="forth">: xt-array here { a } |
|||
10 cells allot 10 0 do |
|||
:noname i ]] literal dup * ; [[ a i cells + ! |
|||
loop a ; |
|||
xt-array 5 cells + @ execute .</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="forth">25</syntaxhighlight> |
|||
=={{header|FreeBASIC}}== |
|||
FreeBASIC doesn't support closures or anonymous methods, as such. However, what we can do is to create an array of objects to capture their index and then call a method on those objects which squares the index. This approach is similar to how some other object oriented languages implement closures 'under the hood'. |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
Type Closure |
|||
Private: |
|||
index As Integer |
|||
Public: |
|||
Declare Constructor(index As Integer = 0) |
|||
Declare Function Square As Integer |
|||
End Type |
|||
Constructor Closure(index As Integer = 0) |
|||
This.index = index |
|||
End Constructor |
|||
Function Closure.Square As Integer |
|||
Return index * index |
|||
End Function |
|||
Dim a(1 To 10) As Closure |
|||
' create Closure objects which capture their index |
|||
For i As Integer = 1 To 10 |
|||
a(i) = Closure(i) |
|||
Next |
|||
' call the Square method on all but the last object |
|||
For i As Integer = 1 to 9 |
|||
Print a(i).Square |
|||
Next |
|||
Print |
|||
Print "Press any key to quit" |
|||
Sleep</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
|||
=={{header|Free Pascal}}== |
|||
FreePascal supports the same syntax als Delphi from version 3.3.1. |
|||
It needs just a couple of defines. |
|||
<syntaxhighlight lang=pascal> |
|||
program testthis; |
|||
{$mode objfpc}{$modeswitch functionreferences}{$modeswitch anonymousfunctions} |
|||
type |
|||
TFuncIntResult = reference to function: Integer; |
|||
// use function that returns anonymous method to avoid capturing the loop variable |
|||
function CreateFunc(i: Integer): TFuncIntResult; |
|||
begin |
|||
Result := |
|||
function: Integer |
|||
begin |
|||
Result := i * i; |
|||
end; |
|||
end; |
|||
var |
|||
Funcs: array[0..9] of TFuncIntResult; |
|||
i: integer; |
|||
begin |
|||
// create 10 anonymous functions |
|||
for i := Low(Funcs) to High(Funcs) do |
|||
Funcs[i] := CreateFunc(i); |
|||
// call all 10 functions |
|||
for i := Low(Funcs) to High(Funcs) do |
|||
Writeln(Funcs[i]()); |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
</pre> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 572: | Line 956: | ||
fmt.Println("func #0:", fs[0]()) |
fmt.Println("func #0:", fs[0]()) |
||
fmt.Println("func #3:", fs[3]()) |
fmt.Println("func #3:", fs[3]()) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 578: | Line 962: | ||
func #3: 9 |
func #3: 9 |
||
</pre> |
</pre> |
||
You don't need to use this trick anymore in Go 1.22+: |
|||
{{works with|Go|1.22+}} |
|||
<syntaxhighlight lang="go">package main |
|||
import "fmt" |
|||
func main() { |
|||
fs := make([]func() int, 10) |
|||
for i := range fs { |
|||
fs[i] = func() int { |
|||
return i * i |
|||
} |
|||
} |
|||
fmt.Println("func #0:", fs[0]()) |
|||
fmt.Println("func #3:", fs[3]()) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
func #0: 0 |
|||
func #3: 9 |
|||
</pre> |
|||
If you take advantage of this, you should declare <pre>go 1.22</pre> in your go.mod file, so that older Go versions will not compile it. See [https://go.dev/blog/loopvar-preview this page] for more information. |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def closures = (0..9).collect{ i -> { -> i*i } }</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="groovy">assert closures instanceof List |
||
assert closures.size() == 10 |
assert closures.size() == 10 |
||
closures.each { assert it instanceof Closure } |
closures.each { assert it instanceof Closure } |
||
println closures[7]()</ |
println closures[7]()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>49</pre> |
<pre>49</pre> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Using <code>map</code>: |
Using <code>map</code>: |
||
< |
<syntaxhighlight lang="haskell">fs = map (\i _ -> i * i) [1 .. 10]</syntaxhighlight> |
||
Using list comprehensions: |
Using list comprehensions: |
||
< |
<syntaxhighlight lang="haskell">fs = [const $ i * i | i <- [1 .. 10]]</syntaxhighlight> |
||
Using infinite lists: |
Using infinite lists: |
||
< |
<syntaxhighlight lang="haskell">fs = take 10 coFs where coFs = [const $ i * i | i <- [1 ..]]</syntaxhighlight> |
||
Testing: |
Testing: |
||
< |
<syntaxhighlight lang="haskell">> :t fs |
||
fs :: [b -> Integer] |
fs :: [b -> Integer] |
||
> map ($ ()) fs |
> map ($ ()) fs |
||
Line 615: | Line 1,021: | ||
100 |
100 |
||
> fs !! 8 $ undefined |
> fs !! 8 $ undefined |
||
81</ |
81</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
This uses Unicon specific calling sequences for co-expressions. It can be made to run under Icon by modifying the calling syntax. |
This uses Unicon specific calling sequences for co-expressions. It can be made to run under Icon by modifying the calling syntax. |
||
< |
<syntaxhighlight lang="Unicon">procedure main(args) # Closure/Variable Capture |
||
every put(L := [], vcapture(1 to 10)) # build list of index closures |
every put(L := [], vcapture(1 to 10)) # build list of index closures |
||
write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure |
write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure |
||
Line 634: | Line 1,039: | ||
procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package |
procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package |
||
return (@A[1], A[1]) |
return (@A[1], A[1]) |
||
end</ |
end</syntaxhighlight> |
||
{{libheader|Unicon Code Library}} |
{{libheader|Unicon Code Library}} |
||
Line 644: | Line 1,049: | ||
<pre>Randomly selecting L[8] = 64</pre> |
<pre>Randomly selecting L[8] = 64</pre> |
||
=={{Header|Insitux}}== |
|||
<syntaxhighlight lang="insitux"> |
|||
(var funcs (for x (range 11) #(* x x))) |
|||
[(0 funcs) ((3 funcs)) ((4 funcs))] |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[#(* x x) 9 16] |
|||
</pre> |
|||
=={{header|Io}}== |
|||
<syntaxhighlight lang="text">blist := list(0,1,2,3,4,5,6,7,8,9) map(i,block(i,block(i*i)) call(i)) |
|||
writeln(blist at(3) call) // prints 9</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
Line 650: | Line 1,072: | ||
The natural way of implementing this in J is to define a function which produces a gerund of a constant function. |
The natural way of implementing this in J is to define a function which produces a gerund of a constant function. |
||
< |
<syntaxhighlight lang="j">constF=:3 :0 |
||
{.''`(y "_) |
{.''`(y "_) |
||
)</ |
)</syntaxhighlight> |
||
Thus, a list of 10 functions each producing a value in 0..9, and another with their squares: |
Thus, a list of 10 functions each producing a value in 0..9, and another with their squares: |
||
< |
<syntaxhighlight lang="j">flist=: constF"0 i.10 |
||
slist=: constF"0 *:i.10</ |
slist=: constF"0 *:i.10</syntaxhighlight> |
||
Referencing a function: |
Referencing a function by its index (its position in that list): |
||
< |
<syntaxhighlight lang="j"> flist @.3 |
||
3"_ |
3"_ |
||
slist @.3 |
slist @.3 |
||
9"_</ |
9"_</syntaxhighlight> |
||
Using a function: |
Using a function, given its index: |
||
< |
<syntaxhighlight lang="j"> flist @.4'' |
||
4 |
4 |
||
slist @.4'' |
slist @.4'' |
||
16</ |
16</syntaxhighlight> |
||
Running a randomly picked function which is not the last one: |
Running a randomly picked function which is not the last one: |
||
< |
<syntaxhighlight lang="j"> flist@.(?9) '' |
||
7 |
7 |
||
slist@.(?9) '' |
slist@.(?9) '' |
||
25</ |
25</syntaxhighlight> |
||
===Using temporary locales=== |
|||
The problem statement "Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over" conflicts with the problem title "Value capture" in languages have sufficient abstraction to distinguish between value capture and variable and variable capture. This conflict even appears in J, and in general cases can require treatment of issues well outside the scope of this task. |
|||
Still, to address the task description, we should include a "variable capture" implementation, which in J could imply the use of "temporary [[j:Vocabulary/Locales#Summary_of_the_Locale_Mechanism|locales]]" despite the fact that this approach would not satisfy the "simplest fashion possible" requirement. |
|||
For example, we could define an adverb 'geni' which takes a base function (which in this case will be <code>*:</code> -- a function which squares an argument) and a value (which in this case will be an index), creates a locale where that value will be stored in a variable named <code>i</code> and then returns an anonymous function which takes a reference to the locale (rather than the value) and extracts the value from the locale to generate the result. |
|||
We'll also use J's nuvoc <code><nowiki>{{</nowiki></code> ... <code><nowiki>}}</nowiki></code> nesting definitional mechanism which implicitly determines the type of a definition instead of explicitly representing the definition types (<code>1 :</code>, <code>2 :</code>, <code>3 :</code>, ...) which discourages nesting blocks. |
|||
<syntaxhighlight lang=J> |
|||
geni=: {{ |
|||
N=. cocreate'' |
|||
i__N=. y |
|||
N |
|||
}} |
|||
task=: {{ u {{ u {{ u i__n [ y }} (geni y)`'' }}"0 i. y }} |
|||
</syntaxhighlight> |
|||
This would be really bad form if we were intending to be useful, but - as described above - this approach is somewhat relevant to the task requirements. |
|||
Example use: |
|||
<syntaxhighlight lang=J> |
|||
fns=: *: task 10 |
|||
fns@.3 '' |
|||
9 |
|||
fns@.5 '' |
|||
25 |
|||
fns@.7 '' |
|||
49 |
|||
</syntaxhighlight> |
|||
===Tacit (unorthodox) version=== |
===Tacit (unorthodox) version=== |
||
In J only adverbs and conjunctions (functionals) can produce verbs (functions)... Unless they are forced to cloak as verbs; in this instance, the rank conjunction (“) cloaks as a dyadic verb. |
In J only adverbs and conjunctions (functionals) can produce verbs (functions)... Unless they are forced to cloak as verbs; in this instance, the rank conjunction (“) cloaks as a dyadic verb. (This does not work in recent versions of J as this takes advantage of a bug/feature where the interpreter does not produce a result with [http://www.jsoftware.com/help/dictionary/dictb.htm the correct shape]): |
||
< |
<syntaxhighlight lang="j"> ( VL=. (<@:((<'"')(0:`)(,^:)&_))"0@:(^&2)@:i. 10 ) NB. Producing a list of boxed anonymous verbs (functions) |
||
┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐ |
┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐ |
||
│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│ |
│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│ |
||
Line 691: | Line 1,145: | ||
25"_ |
25"_ |
||
{::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('') |
{::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('') |
||
25</ |
25</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|8+}} |
{{works with|Java|8+}} |
||
< |
<syntaxhighlight lang="java">import java.util.function.Supplier; |
||
import java.util.ArrayList; |
import java.util.ArrayList; |
||
Line 709: | Line 1,163: | ||
System.out.println(foo.get()); // prints "9" |
System.out.println(foo.get()); // prints "9" |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Alternative implementation that also {{works with|Java|8+}} |
Alternative implementation that also {{works with|Java|8+}} |
||
< |
<syntaxhighlight lang="java">import java.util.List; |
||
import java.util.function.IntSupplier; |
import java.util.function.IntSupplier; |
||
import java.util.stream.IntStream; |
import java.util.stream.IntStream; |
||
Line 728: | Line 1,182: | ||
System.out.println(closure.getAsInt()); // prints "9" |
System.out.println(closure.getAsInt()); // prints "9" |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
<lang javascript>var funcs = []; |
|||
===Imperative=== |
|||
<syntaxhighlight lang="javascript">var funcs = []; |
|||
for (var i = 0; i < 10; i++) { |
for (var i = 0; i < 10; i++) { |
||
funcs.push( (function(i) { |
funcs.push( (function(i) { |
||
Line 737: | Line 1,193: | ||
})(i) ); |
})(i) ); |
||
} |
} |
||
window.alert(funcs[3]()); // alerts "9"</ |
window.alert(funcs[3]()); // alerts "9"</syntaxhighlight> |
||
{{works with|JavaScript|1.7+}} (Firefox 2+) |
{{works with|JavaScript|1.7+}} (Firefox 2+) |
||
< |
<syntaxhighlight lang="javascript"><script type="application/javascript;version=1.7"> |
||
var funcs = []; |
var funcs = []; |
||
for (var i = 0; i < 10; i++) { |
for (var i = 0; i < 10; i++) { |
||
Line 748: | Line 1,204: | ||
} |
} |
||
window.alert(funcs[3]()); // alerts "9" |
window.alert(funcs[3]()); // alerts "9" |
||
</script></ |
</script></syntaxhighlight> |
||
{{works with|JavaScript|ES6}} |
|||
<syntaxhighlight lang="javascript">"use strict"; |
|||
let funcs = []; |
|||
for (let i = 0; i < 10; ++i) { |
|||
funcs.push((i => () => i*i)(i)); |
|||
} |
|||
console.log(funcs[3]());</syntaxhighlight> |
|||
===Functional === |
|||
{{works with|JavaScript|ES5}} |
|||
<syntaxhighlight lang="javascript">(function () { |
|||
'use strict'; |
|||
// Int -> Int -> [Int] |
|||
function range(m, n) { |
|||
return Array.apply(null, Array(n - m + 1)) |
|||
.map(function (x, i) { |
|||
return m + i; |
|||
}); |
|||
} |
|||
var lstFns = range(0, 10) |
|||
.map(function (i) { |
|||
return function () { |
|||
return i * i; |
|||
}; |
|||
}) |
|||
return lstFns[3](); |
|||
})();</syntaxhighlight> |
|||
{{out}} |
|||
<pre>9</pre> |
|||
{{works with|JavaScript|ES6}} |
|||
<syntaxhighlight lang="javascript">let funcs = [...Array(10).keys()].map(i => () => i*i);</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
console.log(funcs[3]()); |
|||
9 |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">funcs = [ () -> i^2 for i = 1:10 ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 757: | Line 1,259: | ||
49 |
49 |
||
</pre> |
</pre> |
||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="scala">// version 1.0.6 |
|||
fun main(args: Array<String>) { |
|||
// create an array of 10 anonymous functions which return the square of their index |
|||
val funcs = Array(10){ fun(): Int = it * it } |
|||
// call all but the last |
|||
(0 .. 8).forEach { println(funcs[it]()) } |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
</pre> |
|||
=={{header|Lambdatalk}}== |
|||
A translation from Javascript |
|||
<syntaxhighlight lang="scheme"> |
|||
{def A |
|||
{A.new |
|||
{S.map {lambda {:x} {* :x :x}} |
|||
{S.serie 0 10} |
|||
}}} |
|||
{A.get 3 {A}} // equivalent to A[3] |
|||
-> 9 |
|||
{A.get 4 {A}} |
|||
-> 16 |
|||
</syntaxhighlight> |
|||
=={{header|Latitude}}== |
|||
Latitude is particularly well suited to this challenge, as the various iteration constructs actually take method arguments and <i>call</i> them multiple times. Thus, the loop variable is in fact an argument which is already closed over and distinct at each iteration. |
|||
<syntaxhighlight lang="latitude">functions := 10 times to (Array) map { |
|||
takes '[i]. |
|||
proc { (i) * (i). }. |
|||
}. |
|||
functions visit { println: $1 call. }.</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81</pre> |
|||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
Input at the REPL: |
Input at the REPL: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (set funcs (list-comp ((<- m (lists:seq 1 10))) |
> (set funcs (list-comp ((<- m (lists:seq 1 10))) |
||
(lambda () (math:pow m 2)))) |
(lambda () (math:pow m 2)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464> |
(#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464> |
||
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464> |
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464> |
||
Line 773: | Line 1,333: | ||
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464> |
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464> |
||
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>) |
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Calling the functions: |
Calling the functions: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (funcall (car funcs)) |
> (funcall (car funcs)) |
||
1.0 |
1.0 |
||
Line 786: | Line 1,346: | ||
64.0 |
64.0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lingo}}== |
|||
Lingo doesn't really support closures. But with the limitations described at [https://www.rosettacode.org/wiki/Function_composition#Lingo Function composition] and based on the fact that Lingo allows to create arbitrary code at runtime, the task can be solved like this: |
|||
<syntaxhighlight lang="lingo">-- parent script "CallFunction" |
|||
property _code |
|||
-- if the function is supposed to return something, the code must contain a line that starts with "res=" |
|||
on new (me, code) |
|||
me._code = code |
|||
return me |
|||
end |
|||
on call (me) |
|||
---------------------------------------- |
|||
-- If custom arguments were passed, evaluate them in the current context. |
|||
-- Note: in the code passed to the constructor they have to be referenced |
|||
-- as arg[1], arg[2], ... |
|||
arg = [] |
|||
repeat with i = 3 to the paramCount |
|||
arg[i-2] = param(i) |
|||
end repeat |
|||
---------------------------------------- |
|||
res = VOID |
|||
do(me._code) |
|||
return res |
|||
end</syntaxhighlight> |
|||
<syntaxhighlight lang="lingo">funcs = [] |
|||
repeat with i = 1 to 10 |
|||
code = "res="&i&"*"&i |
|||
funcs[i] = script("CallFunction").new(code) |
|||
end repeat |
|||
put call(funcs[3], _movie) |
|||
-- 9</syntaxhighlight> |
|||
Since the original task is a little trivial in terms of not depending on runtime arguments, here also a solution for an extended task: let each function[i] return the square of i plus the sum of all arguments passed to it at runtime: |
|||
<syntaxhighlight lang="lingo">funcs = [] |
|||
repeat with i = 1 to 10 |
|||
code = "" |
|||
put "res = "&i&"*"&i &RETURN after code |
|||
put "repeat with i = 1 to arg.count" &RETURN after code |
|||
put " res = res + arg[i]" &RETURN after code |
|||
put "end repeat" after code |
|||
funcs[i] = script("CallFunction").new(code) |
|||
end repeat |
|||
put call(funcs[3], _movie, 23) |
|||
-- 32 |
|||
put call(funcs[7], _movie, 4, 5, 6) |
|||
-- 64</syntaxhighlight> |
|||
=={{header|Logtalk}}== |
=={{header|Logtalk}}== |
||
The example that follow uses Logtalk's native support for lambda expressions. |
The example that follow uses Logtalk's native support for lambda expressions. |
||
< |
<syntaxhighlight lang="logtalk"> |
||
:- object(value_capture). |
:- object(value_capture). |
||
Line 805: | Line 1,420: | ||
:- end_object. |
:- end_object. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="text"> |
||
| ?- value_capture::show. |
| ?- value_capture::show. |
||
Closure 1 : 1 |
Closure 1 : 1 |
||
Line 820: | Line 1,435: | ||
Closure 10 : 100 |
Closure 10 : 100 |
||
yes |
yes |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="Lua"> |
||
funcs={} |
funcs={} |
||
for i=1,10 do |
for i=1,10 do |
||
Line 830: | Line 1,444: | ||
funcs[2]() |
funcs[2]() |
||
funcs[3]() |
funcs[3]() |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>4 |
<pre>4 |
||
9 |
9 |
||
</pre> |
</pre> |
||
=={{header|M2000 Interpreter}}== |
|||
<syntaxhighlight lang="M2000 Interpreter"> |
|||
Dim Base 0, A(10) |
|||
For i=0 to 9 { |
|||
a(i)=lambda i -> i**2 |
|||
} |
|||
For i=0 to 9 { |
|||
Print a(i)() |
|||
} |
|||
</syntaxhighlight> |
|||
Print |
|||
0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
Export list to clipboard |
|||
<syntaxhighlight lang="M2000 Interpreter"> |
|||
document a$ |
|||
For i=0 to 9 { |
|||
a$=format$("{0:0:-20}",a(i)())+{ |
|||
} |
|||
} |
|||
Clipboard a$ |
|||
</syntaxhighlight> |
|||
Using Inventory, and a stack object (reading from position, and another way, we pop functions, using Read) |
|||
<syntaxhighlight lang="M2000 Interpreter"> |
|||
Inventory Alfa |
|||
For i=0 to 9 { |
|||
Append Alfa, i:=lambda i -> i**2 |
|||
} |
|||
For i=0 to 9 { |
|||
Print Alfa(i)() |
|||
} |
|||
Beta=Stack |
|||
Stack Beta { |
|||
For i=0 to 9 { |
|||
Data lambda i -> i**2 |
|||
} |
|||
} |
|||
Def Fun(X)=X() |
|||
\\ reading functions from position 1 to 10 |
|||
For i=0 to 9 { |
|||
Print fun(stackitem(Beta,i+1)) |
|||
} |
|||
\\ pop functions form stack Beta |
|||
Stack Beta { |
|||
While not empty { |
|||
Read M |
|||
Print M() |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="Maple">> L := map( i -> (() -> i^2), [seq](1..10) ): |
||
> seq( L[i](),i=1..10); |
> seq( L[i](),i=1..10); |
||
1, 4, 9, 16, 25, 36, 49, 64, 81, 100 |
1, 4, 9, 16, 25, 36, 49, 64, 81, 100 |
||
> L[4](); |
> L[4](); |
||
16 |
16 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="Mathematica">Function[i, i^2 &] /@ Range@10 |
||
->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &} |
->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &} |
||
%[[2]][] |
%[[2]][] |
||
->4</ |
->4</syntaxhighlight> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="Nemerle">using System.Console; |
||
module Closures |
module Closures |
||
Line 864: | Line 1,539: | ||
WriteLine($"$(funcs[2]())"); |
WriteLine($"$(funcs[2]())"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>16 |
<pre>16 |
||
4</pre> |
4</pre> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">var funcs: seq[proc(): int] = @[] |
||
for i in 0..9: |
for i in 0..9: |
||
(proc = |
|||
let x = i |
|||
funcs.add(proc (): int = x * x))() |
|||
for i in 0..8: |
for i in 0..8: |
||
echo "func[", i, "]: ", funcs[i]()</ |
echo "func[", i, "]: ", funcs[i]()</syntaxhighlight> |
||
=={{header|Objeck}}== |
|||
<syntaxhighlight lang="objeck">use Collection.Generic; |
|||
class Capture { |
|||
function : Main(args : String[]) ~ Nil { |
|||
funcs := Vector->New()<FuncHolder<IntHolder> >; |
|||
for(i := 0; i < 10; i += 1;) { |
|||
funcs->AddBack(FuncHolder->New(\() ~ IntHolder : () => i * i)<IntHolder>); |
|||
}; |
|||
each(i : funcs) { |
|||
func := funcs->Get(i)->Get()<IntHolder>; |
|||
func()->Get()->PrintLine(); |
|||
}; |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
{{works with|Cocoa|Mac OS X 10.6+}} with ARC |
{{works with|Cocoa|Mac OS X 10.6+}} with ARC |
||
< |
<syntaxhighlight lang="objc">NSMutableArray *funcs = [[NSMutableArray alloc] init]; |
||
for (int i = 0; i < 10; i++) { |
for (int i = 0; i < 10; i++) { |
||
[funcs addObject:[^ { return i * i; } copy]]; |
[funcs addObject:[^ { return i * i; } copy]]; |
||
Line 888: | Line 1,594: | ||
int (^foo)(void) = funcs[3]; |
int (^foo)(void) = funcs[3]; |
||
NSLog(@"%d", foo()); // logs "9" |
NSLog(@"%d", foo()); // logs "9" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
All functions in OCaml are closures. |
All functions in OCaml are closures. |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let cls = Array.init 10 (fun i -> (function () -> i * i)) in |
let cls = Array.init 10 (fun i -> (function () -> i * i)) in |
||
Random.self_init (); |
Random.self_init (); |
||
Line 900: | Line 1,605: | ||
let x = Random.int 9 in |
let x = Random.int 9 in |
||
Printf.printf " fun.(%d) = %d\n" x (cls.(x) ()); |
Printf.printf " fun.(%d) = %d\n" x (cls.(x) ()); |
||
done</ |
done</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 911: | Line 1,616: | ||
fun.(6) = 36 |
fun.(6) = 36 |
||
</pre> |
</pre> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="Oforth">: newClosure(i) #[ i sq ] ; |
||
10 seq map(#newClosure) at(7) perform |
10 seq map(#newClosure) at(7) perform .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 920: | Line 1,624: | ||
49 |
49 |
||
</pre> |
</pre> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
{{works with|PARI/GP|2.4.2 and above}} |
{{works with|PARI/GP|2.4.2 and above}} |
||
< |
<syntaxhighlight lang="parigp">vector(10,i,()->i^2)[5]()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>%1 = 25</pre> |
<pre>%1 = 25</pre> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">my @f = map(sub { $_ * $_ }, 0 .. 9); # @f is an array of subs |
||
print $f[$_](), "\n" for (0 .. 8); # call and print all but last</ |
print $f[$_](), "\n" for (0 .. 8); # call and print all but last</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 943: | Line 1,645: | ||
64 |
64 |
||
</pre> |
</pre> |
||
=={{header|Phix}}== |
|||
Phix does not support closures, but they seem easy enough to emulate |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
<span style="color: #000080;font-style:italic;">-- First some generic handling stuff, handles partial_args |
|||
-- of any mixture of any length and element types.</span> |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">closures</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">add_closure</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">partial_args</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #000000;">closures</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">closures</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">partial_args</span><span style="color: #0000FF;">})</span> |
|||
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">closures</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (return an integer id)</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">call_closure</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">id</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">args</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">{</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">partial_args</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">closures</span><span style="color: #0000FF;">[</span><span style="color: #000000;">id</span><span style="color: #0000FF;">]</span> |
|||
<span style="color: #008080;">return</span> <span style="color: #7060A8;">call_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">partial_args</span><span style="color: #0000FF;">&</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<span style="color: #000080;font-style:italic;">-- The test routine to be made into a closure, or ten |
|||
-- Note that all external references/captured variables must |
|||
-- be passed as arguments, and grouped together on the lhs</span> |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">square</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<span style="color: #000080;font-style:italic;">-- Create the ten closures as asked for. |
|||
-- Here, cids is just {1,2,3,4,5,6,7,8,9,10}, however ids would be more |
|||
-- useful for a mixed bag of closures, possibly stored all over the shop. |
|||
-- Likewise add_closure could have been a procedure for this demo, but |
|||
-- you would probably want the function in a real-world application.</span> |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">cids</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #000080;font-style:italic;">--for i=11 to 20 do -- alternative test</span> |
|||
<span style="color: #000000;">cids</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">add_closure</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"square"</span><span style="color: #0000FF;">),{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">})</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<span style="color: #000080;font-style:italic;">-- And finally call em (this loop is blissfully unaware what function |
|||
-- it is actually calling, and what partial_arguments it is passing)</span> |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">call_closure</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cids</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],{}))</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
1 4 9 16 25 36 49 64 81 100 |
|||
</pre> |
|||
output if that 11 to 20 add_closure loop is used instead: |
|||
<pre> |
|||
121 144 169 196 225 256 289 324 361 400 |
|||
</pre> |
|||
Note however that any captured values are effectively immutable, |
|||
unless you also pass the id to the closure, and that in turn |
|||
does rude things to closures[id][2]. |
|||
A dictionary based approach may prove somewhat easier: |
|||
=={{header|Perl 6}}== |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
All blocks are anonymous closures in Perl 6, and parameters are lexicals, so it's easy to generate a list of them. We'll use a <tt>gather</tt>/<tt>take</tt> generator loop, and call the closures in random order, just to keep things interesting. |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
<lang perl6>my @c = gather for ^10 -> $i { |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">square</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">)</span> |
|||
take { $i * $i } |
|||
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"i"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tid</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (setd valid here too)</span> |
|||
} |
|||
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tids</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #000080;font-style:italic;">--for i=11 to 20 do</span> |
|||
<span style="color: #000000;">tids</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"i"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">}})</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">square</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tids</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]))</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<!--</syntaxhighlight>--> |
|||
same output, for both tests |
|||
=={{header|Phixmonti}}== |
|||
<syntaxhighlight lang="phixmonti">def power2 |
|||
dup * |
|||
enddef |
|||
getid power2 10 repeat |
|||
.().say for @c.pick(*); # call them in random order</lang> |
|||
{{out}} |
|||
len for |
|||
<pre>36 |
|||
dup rot swap get rot swap exec print " " print |
|||
64 |
|||
endfor |
|||
25 |
|||
1 |
|||
nl |
|||
16 |
|||
0 |
|||
4 |
|||
9 |
|||
81 |
|||
49</pre> |
|||
Or equivalently, using a more functional notation: |
|||
<lang perl6>say .() for pick *, map -> $i { -> {$i * $i} }, ^10</lang> |
|||
/# Another mode #/ |
|||
len for |
|||
var i |
|||
i get i swap exec print " " print |
|||
endfor</syntaxhighlight> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
{{works with|PHP|5.3+}} |
{{works with|PHP|5.3+}} |
||
< |
<syntaxhighlight lang="php"><?php |
||
$funcs = array(); |
$funcs = array(); |
||
for ($i = 0; $i < 10; $i++) { |
for ($i = 0; $i < 10; $i++) { |
||
Line 973: | Line 1,741: | ||
} |
} |
||
echo $funcs[3](), "\n"; // prints 9 |
echo $funcs[3](), "\n"; // prints 9 |
||
?></ |
?></syntaxhighlight> |
||
{{works with|PHP|pre-5.3}} |
{{works with|PHP|pre-5.3}} |
||
This method can capture value types like numbers, strings, arrays, etc., but not objects. |
This method can capture value types like numbers, strings, arrays, etc., but not objects. |
||
< |
<syntaxhighlight lang="php"><?php |
||
$funcs = array(); |
$funcs = array(); |
||
for ($i = 0; $i < 10; $i++) { |
for ($i = 0; $i < 10; $i++) { |
||
Line 983: | Line 1,751: | ||
} |
} |
||
echo $funcs[3](), "\n"; // prints 9 |
echo $funcs[3](), "\n"; // prints 9 |
||
?></ |
?></syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="PicoLisp">(setq FunList |
||
(make |
(make |
||
(for @N 10 |
(for @N 10 |
||
(link (curry (@N) () (* @N @N))) ) ) )</ |
(link (curry (@N) () (* @N @N))) ) ) )</syntaxhighlight> |
||
Test: |
Test: |
||
<pre>: ((get FunList 2)) |
<pre>: ((get FunList 2)) |
||
Line 996: | Line 1,763: | ||
: ((get FunList 8)) |
: ((get FunList 8)) |
||
-> 64</pre> |
-> 64</pre> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="Pike">array funcs = ({}); |
||
foreach(enumerate(10);; int i) |
foreach(enumerate(10);; int i) |
||
{ |
{ |
||
Line 1,010: | Line 1,776: | ||
}(i) |
}(i) |
||
}); |
}); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PowerShell}}== |
|||
I'm not sure that I understood the question/task. This task seems to be the same as the 'Accumulator Factory' task. |
|||
<syntaxhighlight lang="PowerShell"> |
|||
function Get-Closure ([double]$Number) |
|||
{ |
|||
{param([double]$Sum) return $script:Number *= $Sum}.GetNewClosure() |
|||
} |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="PowerShell"> |
|||
for ($i = 1; $i -lt 11; $i++) |
|||
{ |
|||
$total = Get-Closure -Number $i |
|||
[PSCustomObject]@{ |
|||
Function = $i |
|||
Sum = & $total -Sum $i |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Function Sum |
|||
-------- --- |
|||
1 1 |
|||
2 4 |
|||
3 9 |
|||
4 16 |
|||
5 25 |
|||
6 36 |
|||
7 49 |
|||
8 64 |
|||
9 81 |
|||
10 100 |
|||
</pre> |
|||
<syntaxhighlight lang="PowerShell"> |
|||
$numbers = 1..20 | Get-Random -Count 10 |
|||
foreach ($number in $numbers) |
|||
{ |
|||
$total = Get-Closure -Number $number |
|||
[PSCustomObject]@{ |
|||
Function = $number |
|||
Sum = & $total -Sum $number |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Function Sum |
|||
-------- --- |
|||
4 16 |
|||
16 256 |
|||
3 9 |
|||
17 289 |
|||
9 81 |
|||
15 225 |
|||
7 49 |
|||
6 36 |
|||
1 1 |
|||
20 400 |
|||
</pre> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Works with SWI-Prolog and module '''lambda.pl''' from '''Ulrich Neumerkel'''. <br> |
Works with SWI-Prolog and module '''lambda.pl''' from '''Ulrich Neumerkel'''. <br> |
||
'''lambda.pl''' can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl |
'''lambda.pl''' can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl |
||
< |
<syntaxhighlight lang="Prolog">:-use_module(library(lambda)). |
||
Line 1,030: | Line 1,857: | ||
call(F, R), |
call(F, R), |
||
format('Func ~w : ~w~n', [N, R]). |
format('Func ~w : ~w~n', [N, R]). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> ?- closure. |
<pre> ?- closure. |
||
Line 1,045: | Line 1,872: | ||
true. |
true. |
||
</pre> |
</pre> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
The naive way does not work: |
The naive way does not work: |
||
< |
<syntaxhighlight lang="python">funcs = [] |
||
for i in range(10): |
for i in range(10): |
||
funcs.append(lambda: i * i) |
funcs.append(lambda: i * i) |
||
print funcs[3]() # prints 81</ |
print funcs[3]() # prints 81</syntaxhighlight> |
||
The simplest solution is to add optional parameters with default arguments at the end of the parameter list, to create a local copy of the variable, and evaluate the variable at the time the function is created. (The optional parameter is not expected to ever be passed.) Often, the optional parameter will be named the same as the variable to be closed over (leading to odd-looking code of the form <code>foo=foo</code> in the arguments), so that the code inside the function need not be changed, but this might lead to confusion. This technique does not work for functions with a variable number of arguments. |
The simplest solution is to add optional parameters with default arguments at the end of the parameter list, to create a local copy of the variable, and evaluate the variable at the time the function is created. (The optional parameter is not expected to ever be passed.) Often, the optional parameter will be named the same as the variable to be closed over (leading to odd-looking code of the form <code>foo=foo</code> in the arguments), so that the code inside the function need not be changed, but this might lead to confusion. This technique does not work for functions with a variable number of arguments. |
||
< |
<syntaxhighlight lang="python">funcs = [] |
||
for i in range(10): |
for i in range(10): |
||
funcs.append(lambda i=i: i * i) |
funcs.append(lambda i=i: i * i) |
||
print funcs[3]() # prints 9</ |
print funcs[3]() # prints 9</syntaxhighlight> |
||
or equivalently the list comprehension: |
or equivalently the list comprehension: |
||
< |
<syntaxhighlight lang="python">funcs = [lambda i=i: i * i for i in range(10)] |
||
print funcs[3]() # prints 9</ |
print funcs[3]() # prints 9</syntaxhighlight> |
||
Another solution is to wrap an immediately-executed function around our function. The wrapping function creates a new scope, and its execution forces the evaluation of the variable to be closed over. |
Another solution is to wrap an immediately-executed function around our function. The wrapping function creates a new scope, and its execution forces the evaluation of the variable to be closed over. |
||
< |
<syntaxhighlight lang="python">funcs = [] |
||
for i in range(10): |
for i in range(10): |
||
funcs.append((lambda i: lambda: i * i)(i)) |
funcs.append((lambda i: lambda: i * i)(i)) |
||
print funcs[3]() # prints 9</ |
print funcs[3]() # prints 9</syntaxhighlight> |
||
or equivalently the list comprehension: |
or equivalently the list comprehension: |
||
< |
<syntaxhighlight lang="python">funcs = [(lambda i: lambda: i)(i * i) for i in range(10)] |
||
print funcs[3]() # prints 9</ |
print funcs[3]() # prints 9</syntaxhighlight> |
||
In this case it is also possible to use <code>map()</code> since the function passed to it creates a new scope |
In this case it is also possible to use <code>map()</code> since the function passed to it creates a new scope |
||
< |
<syntaxhighlight lang="python">funcs = map(lambda i: lambda: i * i, range(10)) |
||
print funcs[3]() # prints 9</ |
print funcs[3]() # prints 9</syntaxhighlight> |
||
It is also possible to use <code>eval</code>. |
It is also possible to use <code>eval</code>. |
||
< |
<syntaxhighlight lang="python">funcs=[eval("lambda:%s"%i**2)for i in range(10)] |
||
print funcs[3]() # prints 9</ |
print funcs[3]() # prints 9</syntaxhighlight> |
||
=={{header|Quackery}}== |
|||
Strictly speaking, we could get away with <code>[ table 0 1 4 9 16 25 36 49 64 81 ] is functions ( n --> n )</code> for this task, as numbers in Quackery are functions that return their own value when executed, e.g <code>5 do</code> returns <code>5</code>, but it feels like cheating. |
|||
<syntaxhighlight lang="Quackery"> [ table ] is functions ( n --> [ ) |
|||
10 times |
|||
[ i^ ' [ dup * ] join |
|||
' functions put ] |
|||
5 functions do echo</syntaxhighlight> |
|||
{{out}} |
|||
<pre>25</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
Line 1,086: | Line 1,926: | ||
what you expect. |
what you expect. |
||
<syntaxhighlight lang="R"> |
|||
<lang R> |
|||
# assign 's' a list of ten functions |
# assign 's' a list of ten functions |
||
s <- sapply (1:10, # integers 1..10 become argument 'x' below |
s <- sapply (1:10, # integers 1..10 become argument 'x' below |
||
Line 1,096: | Line 1,936: | ||
s[[5]]() # call the fifth function in the list of returned functions |
s[[5]]() # call the fifth function in the list of returned functions |
||
[1] 25 # returns vector of length 1 with the value 25 |
[1] 25 # returns vector of length 1 with the value 25 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note that I bound the captured variable as the default argument on a unary function. |
Note that I bound the captured variable as the default argument on a unary function. |
||
Line 1,102: | Line 1,942: | ||
ignores the default argument. |
ignores the default argument. |
||
<syntaxhighlight lang="R"> |
|||
<lang R> |
|||
s[[5]](10) |
s[[5]](10) |
||
[1] 100 |
[1] 100 |
||
</syntaxhighlight> |
|||
</lang> |
|||
As a further technicality, note that you need some extra voodoo to '''modify''' the bound argument |
As a further technicality, note that you need some extra voodoo to '''modify''' the bound argument |
||
with persistence across calls. This example increments the bound variable after each call. |
with persistence across calls. This example increments the bound variable after each call. |
||
<syntaxhighlight lang="R"> |
|||
<lang R> |
|||
s <- sapply (1:10, |
s <- sapply (1:10, |
||
function (x) { |
function (x) { |
||
Line 1,129: | Line 1,969: | ||
s[[1]]() |
s[[1]]() |
||
[1] 4 # now 2^2 |
[1] 4 # now 2^2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
As shown, each instance increments separately. |
As shown, each instance increments separately. |
||
<b>--- Edit ---</b> |
|||
I think that modifying the bound variable can be done in a simpler way. |
|||
Instead of: |
|||
<syntaxhighlight lang="R"> evalq (x <- x + 1, parent.env(environment()))</syntaxhighlight> |
|||
substitute: |
|||
<syntaxhighlight lang="R"> x <<- x + 1</syntaxhighlight> |
|||
Testing: |
|||
<pre> |
|||
> s[[5]]() |
|||
[1] 25 |
|||
> s[[5]]() |
|||
[1] 36 |
|||
> s[[5]]() |
|||
[1] 49 |
|||
> s[[2]]() |
|||
[1] 4 |
|||
> s[[2]]() |
|||
[1] 9 |
|||
> s[[2]]() |
|||
[1] 16 |
|||
</pre> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(define functions (for/list ([i 10]) (λ() (* i i)))) |
(define functions (for/list ([i 10]) (λ() (* i i)))) |
||
(map (λ(f) (f)) functions) |
(map (λ(f) (f)) functions) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="racket"> |
||
'(0 1 4 9 16 25 36 49 64 81) |
'(0 1 4 9 16 25 36 49 64 81) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
{{Works with|Rakudo|2015.12}} |
|||
All blocks are anonymous closures in Raku, and parameters are lexicals, so it's easy to generate a list of them. We'll use a <tt>gather</tt>/<tt>take</tt> generator loop, and call the closures in random order, just to keep things interesting. |
|||
<syntaxhighlight lang="raku" line>my @c = gather for ^10 -> $i { |
|||
take { $i * $i } |
|||
} |
|||
.().say for @c.pick(*); # call them in random order</syntaxhighlight> |
|||
{{out}} |
|||
<pre>36 |
|||
64 |
|||
25 |
|||
1 |
|||
16 |
|||
0 |
|||
4 |
|||
9 |
|||
81 |
|||
49</pre> |
|||
Or equivalently, using a more functional notation: |
|||
<syntaxhighlight lang="raku" line>say .() for pick *, map -> $i { -> {$i * $i} }, ^10</syntaxhighlight> |
|||
=={{header|Red}}== |
|||
<syntaxhighlight lang="Red"> |
|||
funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]] |
|||
>> funs/7 |
|||
== 49 |
|||
</syntaxhighlight> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
This REXX version supports both a one─ and zero─based list (it can be specified at the command line.) |
|||
<lang rexx>/*REXX pgm has a list of 10 functions, each returns its invocation(idx)²*/ |
|||
The default is to use a zero─based list. |
|||
do j=1 for 9 /*invoke random functions 9 times.*/ |
|||
interpret 'CALL .'random(0,9) /*invoke a randomly selected func.*/ |
|||
end /*j*/ /* [↑] the random func has no args*/ |
|||
The list can also be specified at the command line. The default is an ordered list based on an obscure sequence (but puzzle enthusiasts can figure it out). |
|||
say 'The tenth invocation of .0 ───► ' .0() |
|||
exit /*stick a fork in it, we're done.*/ |
|||
No error checking is performed on the user input(s). |
|||
/*─────────────────────────────────list of 10 functions─────────────────*/ |
|||
<syntaxhighlight lang="rexx">/*REXX program has a list of ten functions, each returns its invocation (index) squared.*/ |
|||
/*[Below is the closest thing to anonymous functions in the REXX lang.] */ |
|||
parse arg seed base $ /*obtain optional arguments from the CL*/ |
|||
.0:return .(); .1:return .(); .2:return .(); .3:return .(); .4:return .() |
|||
if datatype(seed, 'W') then call random ,,seed /*Not given? Use random start seed. */ |
|||
.5:return .(); .6:return .(); .7:return .(); .8:return .(); .9:return .() |
|||
if base=='' | base="," then base=0 /* " " Use a zero─based list. */ |
|||
/*─────────────────────────────────. function───────────────────────────*/ |
|||
if $='' then $= 8 5 4 9 1 3 2 7 6 0 /* " " Use ordered function list*/ |
|||
.: if symbol('@')=='LIT' then @=0 /*handle 1st invoke*/; @=@+1; return @*@</lang> |
|||
/*the $ list must contain 10 functions.*/ |
|||
{{out}} |
|||
say 'the' word("zero one", base+1)'─based list is: ' $ /*show list of functions.*/ |
|||
/*BASED must be either 1 or 0. */ |
|||
?='.'random(0, 9) /*get a random name of a function. */ |
|||
interpret 'CALL' ? /*invoke a randomly selected function. */ |
|||
say 'function ' ? " returned " result /*display the value of random function.*/ |
|||
exit /*stick a fork in it, we're all done. */ |
|||
/*────────────────────────[Below are the closest things to anonymous functions in REXX].*/ |
|||
.0: return .(0) /*function .0 ─── bump its counter. */ |
|||
.1: return .(1) /* ' .1 " " " " */ |
|||
.2: return .(2) /* ' .2 " " " " */ |
|||
.3: return .(3) /* ' .3 " " " " */ |
|||
.4: return .(4) /* ' .4 " " " " */ |
|||
.5: return .(5) /* ' .5 " " " " */ |
|||
.6: return .(6) /* ' .6 " " " " */ |
|||
.7: return .(7) /* ' .7 " " " " */ |
|||
.8: return .(8) /* ' .8 " " " " */ |
|||
.9: return .(9) /* ' .9 " " " " */ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
.: arg #; _=wordpos(#,$); if _==0 then return 'not in the list.'; return (_-(\base))**2</syntaxhighlight> |
|||
{{out|output|text= when using the default input which assume a zero─based list):}} |
|||
<pre> |
<pre> |
||
the zero─based list is: 8 5 4 9 1 3 2 7 6 0 |
|||
The tenth invocation of .0 ───► 100 |
|||
function .0 returned 81 |
|||
</pre> |
</pre> |
||
{{out|output|text= when using the input of: <tt> , 1 </tt>}} |
|||
<pre> |
|||
the one─based list is: 8 5 4 9 1 3 2 7 6 0 |
|||
function .0 returned 100 |
|||
</pre> |
|||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
x = funcs(7) |
|||
see x + nl |
|||
func funcs n |
|||
fn = list(n) |
|||
for i = 1 to n |
|||
fn[i] =i*i |
|||
next |
|||
return fn |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<syntaxhighlight lang="ruby">procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda |
|||
<lang ruby>list = {} |
|||
p procs[7].call # => 49</syntaxhighlight> |
|||
(1..10).each {|i| list[i] = proc {i * i}} |
|||
p list[3].call #=> 9 |
|||
p list[7][] #=> 49 |
|||
i = 5 |
|||
p list[3].call #=> 9</lang> |
|||
This works because ''i'' in <code>(1..10).each {|i| ...}</code> is local to its block. The loop calls the block 10 times, so there are 10 different variables to capture. |
|||
With Ruby 1.9, ''i'' is always local to its block. With Ruby 1.8, ''i'' is local unless there is another ''i'' in the outer scope. If ''i'' is not local, all 10 procs will return 100. |
|||
However, (on both Ruby 1.8 and 1.9) when using a for loop, the loop variable is shared and not local to each iteration: |
|||
<lang ruby>list = {} |
|||
for i in 1..10 do list[i] = proc {i * i} end |
|||
p list[3][] #=> 100 |
|||
i = 5 |
|||
p list[3][] #=> 25</lang> |
|||
In Ruby, lambdas (and procs) are closures. |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
One note here about referencing values and capturing values: <br> |
One note here about referencing values and capturing values: <br> |
||
Rust employs strong ownership rules that do not allow mutating a value that is referenced (pointed to without allowing mutation) from elsewhere. It also doesn't allow referencing a value that may be dropped before the reference is released. The proof that we really did capture the value is therefore unnecessary. Either we did or it wouldn't have compiled. |
Rust employs strong ownership rules that do not allow mutating a value that is referenced (pointed to without allowing mutation) from elsewhere. It also doesn't allow referencing a value that may be dropped before the reference is released. The proof that we really did capture the value is therefore unnecessary. Either we did or it wouldn't have compiled. |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect(); |
let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect(); |
||
println!("7th val: {}", fs[7]()); |
println!("7th val: {}", fs[7]()); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>7th val: 49</pre> |
<pre>7th val: 49</pre> |
||
=={{header|Scala}}== |
|||
<syntaxhighlight lang="scala">val closures=for(i <- 0 to 9) yield (()=>i*i) |
|||
0 to 8 foreach (i=> println(closures(i)())) |
|||
println("---\n"+closures(7)())</syntaxhighlight> |
|||
{{out}} |
|||
<pre>0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
--- |
|||
49</pre> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">;;; Collecting lambdas in a tail-recursive function. |
||
(define (build-list-of-functions n i list) |
(define (build-list-of-functions n i list) |
||
(if (< i n) |
(if (< i n) |
||
Line 1,207: | Line 2,144: | ||
(map (lambda (f) (f)) list-of-functions) |
(map (lambda (f) (f)) list-of-functions) |
||
((list-ref list-of-functions 8))</ |
((list-ref list-of-functions 8))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="scheme">'(1 4 9 16 25 36 49 64 81) |
||
81</ |
81</syntaxhighlight> |
||
---- |
---- |
||
Using Scheme [http://srfi.schemers.org/srfi-1/srfi-1.html SRFI 1] ''iota'' procedure can be simplified to: |
Using Scheme [http://srfi.schemers.org/srfi-1/srfi-1.html SRFI 1] ''iota'' procedure can be simplified to: |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define list-of-functions (map (lambda (x) (lambda () (* x x))) (iota 0 1 10))) |
(define list-of-functions (map (lambda (x) (lambda () (* x x))) (iota 0 1 10))) |
||
Line 1,223: | Line 2,160: | ||
(map (lambda (n) (n)) list-of-functions) |
(map (lambda (n) (n)) list-of-functions) |
||
(newline) |
(newline) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sidef}}== |
|||
<syntaxhighlight lang="ruby">var f = ( |
|||
10.of {|i| func(j){i * j} } |
|||
) |
|||
9.times { |j| |
|||
=={{header|Scala}}== |
|||
say f[j](j) |
|||
<lang scala>val closures=for(i <- 0 to 9) yield (()=>i*i) |
|||
}</syntaxhighlight> |
|||
0 to 8 foreach (i=> println(closures(i)())) |
|||
println("---\n"+closures(7)())</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
0 |
|||
1 |
1 |
||
4 |
4 |
||
Line 1,239: | Line 2,180: | ||
49 |
49 |
||
64 |
64 |
||
</pre> |
|||
--- |
|||
49</pre> |
|||
Starting from i=1: |
|||
=={{header|Sidef}}== |
|||
< |
<syntaxhighlight lang="ruby">var f = (1..10).map { |i| |
||
func(j){i * j} |
|||
} |
|||
); |
|||
for j (1..9) { |
|||
0 ..^ 8 -> each { |j| |
|||
say f[j] |
say f[j-1](j) |
||
}</syntaxhighlight> |
|||
};</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
0 |
|||
1 |
1 |
||
4 |
4 |
||
Line 1,261: | Line 2,200: | ||
49 |
49 |
||
64 |
64 |
||
81 |
|||
</pre> |
</pre> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">funcs := (1 to: 10) collect: [ :i | [ i * i ] ] . |
||
(funcs at: 3) value displayNl .</ |
(funcs at: 3) value displayNl .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>9</pre> |
<pre>9</pre> |
||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
In Sparkling, upvalues (variables in the closure) are captured by value. |
In Sparkling, upvalues (variables in the closure) are captured by value. |
||
< |
<syntaxhighlight lang="sparkling">var fnlist = {}; |
||
for var i = 0; i < 10; i++ { |
for var i = 0; i < 10; i++ { |
||
fnlist[i] = function() { |
fnlist[i] = function() { |
||
Line 1,280: | Line 2,218: | ||
print(fnlist[3]()); // prints 9 |
print(fnlist[3]()); // prints 9 |
||
print(fnlist[5]()); // prints 25</ |
print(fnlist[5]()); // prints 25</syntaxhighlight> |
||
Alternately: |
Alternately: |
||
< |
<syntaxhighlight lang="sparkling">var fnlist = map(range(10), function(k, v) { |
||
return function() { |
return function() { |
||
return v * v; |
return v * v; |
||
Line 1,291: | Line 2,229: | ||
print(fnlist[3]()); // prints 9 |
print(fnlist[3]()); // prints 9 |
||
print(fnlist[5]()); // prints 25</ |
print(fnlist[5]()); // prints 25</syntaxhighlight> |
||
=={{header|Standard ML}}== |
|||
<syntaxhighlight lang="Standard ML"> |
|||
List.map (fn x => x () ) ( List.tabulate (10,(fn i => (fn ()=> i*i)) ) ) ; |
|||
</syntaxhighlight> Output: |
|||
<syntaxhighlight lang="Standard ML"> |
|||
val it = [0,1,4,9,16,25,36,49,64,81] : int list |
|||
</syntaxhighlight> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
By default, Swift captures variables by reference. A naive implementation like the following C-style for loop does not work: |
By default, Swift captures variables by reference. A naive implementation like the following C-style for loop does not work: |
||
< |
<syntaxhighlight lang="swift">var funcs: [() -> Int] = [] |
||
for var i = 0; i < 10; i++ { |
for var i = 0; i < 10; i++ { |
||
funcs.append({ i * i }) |
funcs.append({ i * i }) |
||
} |
} |
||
println(funcs[3]()) // prints 100</ |
println(funcs[3]()) // prints 100</syntaxhighlight> |
||
However, using a for-in loop over a range does work, since you get a new constant at every iteration: |
However, using a for-in loop over a range does work, since you get a new constant at every iteration: |
||
< |
<syntaxhighlight lang="swift">var funcs: [() -> Int] = [] |
||
for i in 0..<10 { |
for i in 0..<10 { |
||
funcs.append({ i * i }) |
funcs.append({ i * i }) |
||
} |
} |
||
println(funcs[3]()) // prints 9</ |
println(funcs[3]()) // prints 9</syntaxhighlight> |
||
The C-style for loop can also work if we explicitly capture the loop counter: |
The C-style for loop can also work if we explicitly capture the loop counter: |
||
< |
<syntaxhighlight lang="swift">var funcs: [() -> Int] = [] |
||
for var i = 0; i < 10; i++ { |
for var i = 0; i < 10; i++ { |
||
funcs.append({ [i] in i * i }) |
funcs.append({ [i] in i * i }) |
||
} |
} |
||
println(funcs[3]()) // prints 9</ |
println(funcs[3]()) // prints 9</syntaxhighlight> |
||
Alternately, we can also use <code>map()</code> to map over a range, and create the squaring closure inside the mapping closure which has the integer as a parameter: |
Alternately, we can also use <code>map()</code> to map over a range, and create the squaring closure inside the mapping closure which has the integer as a parameter: |
||
< |
<syntaxhighlight lang="swift">let funcs = [] + map(0..<10) {i in { i * i }} |
||
println(funcs[3]()) // prints 9</ |
println(funcs[3]()) // prints 9</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Tcl does not support closures (either value-capturing or variable-capturing) by default, but value-capturing closures are easy to emulate. |
Tcl does not support closures (either value-capturing or variable-capturing) by default, but value-capturing closures are easy to emulate. |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6; # Just for tailcall command |
||
# Builds a value-capturing closure; does NOT couple variables |
# Builds a value-capturing closure; does NOT couple variables |
||
proc closure {script} { |
proc closure {script} { |
||
Line 1,356: | Line 2,299: | ||
set idx [expr {int(rand()*9)}]; # pick random int from [0..9) |
set idx [expr {int(rand()*9)}]; # pick random int from [0..9) |
||
puts $idx=>[{*}[lindex $theClosures $idx]] |
puts $idx=>[{*}[lindex $theClosures $idx]] |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,365: | Line 2,308: | ||
8=>64 |
8=>64 |
||
</pre> |
</pre> |
||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
====Sugared==== |
|||
<lang txrlisp>(let ((funs (mapcar (ret (op * @@1 @@1)) (range 1 10)))) |
|||
[mapcar call funs])</lang> |
|||
<syntaxhighlight lang="txrlisp">(let ((funs (mapcar (ret (op * @@1 @@1)) (range 1 10)))) |
|||
[mapcar call [funs 0..-1]])</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="txrlisp">(1 4 9 16 25 36 49 64 81)</syntaxhighlight> |
||
====Desugared==== |
|||
{{trans|Emacs Lisp}} |
|||
The explicit <code>lambda</code> structure here is much like the implicit ones in the "Sugared" example: |
|||
<syntaxhighlight lang="txrlisp">;; Dropping distracting "skip last" requirement |
|||
;; (not implemented in original Elisp either). |
|||
(mapcar 'call |
|||
(mapcar (lambda () |
|||
(lambda () (* x x))) '(1 2 3 4 5 6 7 8 9 10)))</syntaxhighlight> |
|||
====Delimited Continuations==== |
|||
In this interactive example, we capture delimited continuations inside a simple <code>for</code> loop. Because the variable binding environment is not necessarily in the stack which is captured, we rebind the loop variable. |
|||
<pre>This is the TXR Lisp interactive listener of TXR 124. |
|||
Use the :quit command or type Ctrl-D on empty line to exit. |
|||
1> (let ((conts)) |
|||
(for ((i 0)) ((< i 10) (nreverse conts)) ((inc i)) |
|||
(let ((cap i)) |
|||
(push (block sqr |
|||
(suspend sqr f (op f nil)) |
|||
(* cap cap)) |
|||
conts)))) |
|||
(#<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> |
|||
#<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> |
|||
#<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> |
|||
#<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> |
|||
#<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112>) |
|||
2> (call (first *1)) |
|||
0 |
|||
3> (call (second *1)) |
|||
1 |
|||
4> (call (fifth *1)) |
|||
16 |
|||
5> (call [*1 4]) |
|||
16 |
|||
6> (call [*1 7]) |
|||
49</pre> |
|||
The <code>suspend</code> operator suspends the execution of the <code>sqr</code> block, causing it to return the function <code>(op f nil)</code>. The variable <code>f</code> represents the captured continuation as a function. Continuation functions take one mandatory argument. We don't need that here, hence the <code>(op f nil)</code> expression is returned: it curries the one arg continuation function <code>f</code> to a function with no arguments. |
|||
The loop pushes these suspended continuations into a list, and then <code>nreverse</code>-s it. |
|||
We then interactively call the continuations in the list. |
|||
Whenever we call a continuation, the <code>(block sqr ...)</code> environment is restored. and the suspended computation inside the block resumes by returning out of the <code>(suspend ...)</code> form normally. The block then executes to completion, returning the <code>(* cap cap)</code> form's value. At that point, our call to the continuation terminates, yielding that value. |
|||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">var fs = List.filled(10, null) |
|||
for (i in 0...fs.count) { |
|||
fs[i] = Fn.new { i * i } |
|||
} |
|||
for (i in 0...fs.count-1) System.print("Function #%(i): %(fs[i].call())")</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Function #0: 0 |
|||
Function #1: 1 |
|||
Function #2: 4 |
|||
Function #3: 9 |
|||
Function #4: 16 |
|||
Function #5: 25 |
|||
Function #6: 36 |
|||
Function #7: 49 |
|||
Function #8: 64 |
|||
</pre> |
|||
=={{header|Yabasic}}== |
|||
<syntaxhighlight lang="Yabasic"> |
|||
dim funcs$(10) |
|||
sub power2(i) |
|||
return i * i |
|||
end sub |
|||
for i = 1 to 10 |
|||
funcs$(i) = "power2" |
|||
next |
|||
for i = 1 to 10 |
|||
print execute(funcs$(i), i) |
|||
next |
|||
</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Create a closure of the index over a square function |
Create a closure of the index over a square function |
||
< |
<syntaxhighlight lang="zkl">(0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64 |
||
list:=(0).pump(10,List,fcn(i){i*i}.fp); |
list:=(0).pump(10,List,fcn(i){i*i}.fp); |
||
foreach n in (list.len()-1) { list[n]().println() } |
foreach n in (list.len()-1) { list[n]().println() } |
||
list.run(True).println()</ |
list.run(True).println()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,394: | Line 2,423: | ||
L(0,1,4,9,16,25,36,49,64,81) |
L(0,1,4,9,16,25,36,49,64,81) |
||
</pre> |
</pre> |
||
{{omit from|BASIC}} |
{{omit from|BASIC}} |
||
{{omit from|Brlcad}} |
{{omit from|Brlcad}} |
||
Line 1,401: | Line 2,429: | ||
{{omit from|PureBasic}} |
{{omit from|PureBasic}} |
||
{{omit from|ZX Spectrum Basic}} |
{{omit from|ZX Spectrum Basic}} |
||
[[Category:Functions and subroutines]] |
Latest revision as of 13:48, 23 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
- Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
11l
[(() -> Int)] funcs
L(i) 10
funcs.append(() -> @=i * @=i)
print(funcs[3]())
- Output:
9
Acornsoft Lisp
Since this Lisp is dynamically scoped and does not have any built-in closure mechanism, we have to construct one which we'll call freeze
. (The name is inspired by the Pop-2 programming languages's "frozen formals".)
(freeze varlist lambda-expr) finds the current values of the variables in varlist and returns a lambda-expression that is like the original except that, when called, it binds those variables to their captured values. For example, if a
's value is 1 and b
's is 2,
(freeze '(a b) '(lambda (c) (list a b c)))
would return
(lambda (c)
((lambda ((a . 1) (b . 2))
(list a b c))))
What does that mean? A cons (name . value) in a lambda-expressions's formal parameters is the syntax for a formal with a default value. The value is literally the value; it's not an expression that's evaluated. This
( (lambda ((a . 1) (b . 2))
(list a b c)) )
calls the function represented by that lambda-expression. Since it does not give the function any arguments, a
and b
get their default values (which are the values captured by freeze
).
(Although code within such a 'closure' can assign new values to the captured variables, it would have only a temporary effect and would not change the values seen in subsequent calls to the same closure. That's one sense in which the variable values are "frozen".)
Here is the definition of freeze
:
(defun freeze (_fvars_ _lambda-expr_)
(freeze-vars
(mapc cons _fvars_ (mapc eval _fvars_))
(cadr _lambda-expr_)
(cddr _lambda-expr_)))
(defun freeze-vars (bindings lvars lbody)
(list 'lambda lvars
(list (cons 'lambda (cons bindings lbody)))))
Once we have freeze
, we can create a list of square-returning functions and then call them:
(defun range (from to)
(cond ((greaterp from to) '())
(t (cons from (range (add1 from) to)))))
(defun example ()
(mapc '(lambda (f) (f))
(mapc '(lambda (i)
(freeze '(i) '(lambda () (times i i))))
(range 1 10))))
- Output:
(example)
returns
(1 4 9 16 25 36 49 64 81 100)
Ada
One way to realize closures in Ada is the usage of protected objects.
with Ada.Text_IO;
procedure Value_Capture is
protected type Fun is -- declaration of the type of a protected object
entry Init(Index: Natural);
function Result return Natural;
private
N: Natural := 0;
end Fun;
protected body Fun is -- the implementation of a protected object
entry Init(Index: Natural) when N=0 is
begin -- after N has been set to a nonzero value, it cannot be changed any more
N := Index;
end Init;
function Result return Natural is (N*N);
end Fun;
A: array (1 .. 10) of Fun; -- an array holding 10 protected objects
begin
for I in A'Range loop -- initialize the protected objects
A(I).Init(I);
end loop;
for I in A'First .. A'Last-1 loop -- evaluate the functions, except for the last
Ada.Text_IO.Put(Integer'Image(A(I).Result));
end loop;
end Value_Capture;
- Output:
1 4 9 16 25 36 49 64 81
ALGOL 68
[1:10]PROC(BOOL)INT squares;
FOR i FROM 1 TO 10 DO
HEAP INT captured i := i;
squares[i] := ((REF INT by ref i, INT by val i,BOOL b)INT:(INT i = by ref i; (b|by ref i := 0); by val i*i))
(captured i, captured i,)
OD;
FOR i FROM 1 TO 8 DO print(squares[i](i MOD 2 = 0)) OD;
print(new line);
FOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD
- Output:
+1 +4 +9 +16 +25 +36 +49 +64 +1 +0 +9 +0 +25 +0 +49 +0 +81 +100
Using partial parametrization as proposed in Algol Bulletin by Charles Lindsey. Algol68G does not support binding all actual parameters "partially" without deproceduring, so a PROC(BOOL)INT mode is used instead of a PROC INT. The variable captured i is passed twice, once by reference and once by value, to demonstrate that it is possible to capture both ways, and a little extra code is added to show that the closure can modify the captured variable.
AntLang
fns: {n: x; {n expt 2}} map range[10]
(8 elem fns)[]
AppleScript
on run
set fns to {}
repeat with i from 1 to 10
set end of fns to closure(i)
end repeat
|λ|() of item 3 of fns
end run
on closure(x)
script
on |λ|()
x * x
end |λ|
end script
end closure
- Output:
9
Or, in a more functional pattern of composition:
-- CLOSURE --------------------------------------------------------------------
script closure
on |λ|(x)
script
on |λ|()
x * x
end |λ|
end script
end |λ|
end script
|λ|() of (item 3 of (map(closure, enumFromTo(1, 10))))
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
9
Arturo
funcs: [ø]
loop 1..10 'f ->
'funcs ++ function [] with 'f [
f * f
]
print call funcs\3 []
- Output:
9
Axiom
Using the Spad compiler:
)abbrev package TESTP TestPackage
TestPackage() : with
test: () -> List((()->Integer))
== add
test() == [(() +-> i^2) for i in 1..10]
This can be called from the interpreter using:
[x() for x in test()]
- Output:
[1,4,9,16,25,36,49,64,81,100]
Type: List(Integer)
Babel
((main {
{ iter
1 take bons 1 take
dup cp
{*} cp
3 take
append }
10 times
collect !
{eval %d nl <<} each }))
- Output:
100
81
64
49
36
25
16
9
4
1
Essentially, a function has been constructed for each value to be squared (10 down to 1). The cp operator ensures that we generate a fresh copy of the number to be squared, as well as the code for multiplying, {*}. In the final each loop, we eval each of the constructed functions and output the result.
Bracmat
( -1:?i
& :?funcs
& whl
' ( 1+!i:<10:?i
& !funcs ()'(.$i^2):?funcs
)
& whl'(!funcs:%?func %?funcs&out$(!func$))
);
- Output:
0 1 4 9 16 25 36 49 64
C
Function image copying approach
Non-portable. Copying a function body depends on implementation-specific semantics of volatile, if the replacement target still exists after optimization, if the dest memory is suitably aligned, if the memory is executable, if it makes any function calls to a relative offset, if it refers to any memory location with an absolute address, etc. It only very occasionally works.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
typedef int (*f_int)();
#define TAG 0xdeadbeef
int _tmpl() {
volatile int x = TAG;
return x * x;
}
#define PROT (PROT_EXEC | PROT_WRITE)
#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS)
f_int dupf(int v)
{
size_t len = (void*)dupf - (void*)_tmpl;
f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);
char *p;
if(ret == MAP_FAILED) {
perror("mmap");
exit(-1);
}
memcpy(ret, _tmpl, len);
for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)
if (*(int *)p == TAG) *(int *)p = v;
return ret;
}
int main()
{
f_int funcs[10];
int i;
for (i = 0; i < 10; i++) funcs[i] = dupf(i);
for (i = 0; i < 9; i++)
printf("func[%d]: %d\n", i, funcs[i]());
return 0;
}
- Output:
func[0]: 0
func[1]: 1
func[2]: 4
func[3]: 9
func[4]: 16
func[5]: 25
func[6]: 36
func[7]: 49
func[8]: 64
Greenspunned mini Lisp dialect
See Closures/Variable_capture/C for complete code. The relevant excerpt is:
void init(void)
{
t = intern(lit("t"));
x = intern(lit("x"));
}
val square(val env)
{
val xbind = assoc(env, x); /* look up binding of variable x in env */
val xval = cdr(xbind); /* value is the cdr of the binding cell */
return num(cnum(xval) * cnum(xval));
}
int main(void)
{
int i;
val funlist = nil, iter;
init();
for (i = 0; i < 10; i++) {
val closure_env = cons(cons(x, num(i)), nil);
funlist = cons(func_f0(closure_env, square), funlist);
}
for (iter = funlist; iter != nil; iter = cdr(iter)) {
val fun = car(iter);
val square = funcall(fun, nao);
printf("%d\n", cnum(square));
}
return 0;
}
Here, we create an environment explicitly as an association list
which we can search with the assoc
function.
The environment contains a binding for the symbol x
.
The square
function retrieves the value and returns its square.
- Output:
$ ./a.out 81 64 49 36 25 16 9 4 1 0
C#
Using Linq
using System;
using System.Linq;
class Program
{
static void Main()
{
var captor = (Func<int, Func<int>>)(number => () => number * number);
var functions = Enumerable.Range(0, 10).Select(captor);
foreach (var function in functions.Take(9))
{
Console.WriteLine(function());
}
}
}
- Output:
0
1
4
9
16
25
36
49
64
Using delegates only
using System;
using System.Collections.Generic;
class Program
{
static void Main( string[] args )
{
List<Func<int>> l = new List<Func<int>>();
for ( int i = 0; i < 10; ++i )
{
// This is key to avoiding the closure trap, because
// the anonymous delegate captures a reference to
// outer variables, not their value. So we create 10
// variables, and each created anonymous delegate
// has references to that variable, not the loop variable
var captured_val = i;
l.Add( delegate() { return captured_val * captured_val; } );
}
l.ForEach( delegate( Func<int> f ) { Console.WriteLine( f() ); } );
}
}
- Output:
0
1
4
9
16
25
36
49
64
C++
#include <iostream>
#include <functional>
#include <vector>
int main() {
std::vector<std::function<int()> > funcs;
for (int i = 0; i < 10; i++)
funcs.push_back([=]() { return i * i; });
for ( std::function<int( )> f : funcs )
std::cout << f( ) << std::endl ;
return 0;
}
- Output:
0 1 4 9 16 25 36 49 64 81
Ceylon
shared void run() {
//create a list of closures with a list comprehension
value closures = [for(i in 0:10) () => i ^ 2];
for(i->closure in closures.indexed) {
print("closure number ``i`` returns: ``closure()``");
}
}
Clojure
(def funcs (map #(fn [] (* % %)) (range 11)))
(printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
- Output:
9 16
CoffeeScript
# Generate an array of functions.
funcs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i )
# Call each function to demonstrate value capture.
console.log func() for func in funcs
Common Lisp
CL-USER> (defparameter alist
(loop for i from 1 to 10
collect (cons i (let ((i i))
(lambda () (* i i))))))
ALIST
CL-USER> (funcall (cdr (assoc 2 alist)))
4
CL-USER> (funcall (cdr (assoc 8 alist)))
64
The loop mutates its binding i. The purpose of (let ((i i)) ...)
is to create a different binding i for each lambda to capture. Otherwise, all 10 lambdas would capture the same binding and return 100.
D
Less Functional Version
import std.stdio;
void main() {
int delegate()[] funcs;
foreach (i; 0 .. 10)
funcs ~= (i => () => i ^^ 2)(i);
writeln(funcs[3]());
}
- Output:
9
More Functional Version
void main() {
import std.stdio, std.range, std.algorithm;
10.iota.map!(i => () => i ^^ 2).map!q{ a() }.writeln;
}
- Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Delphi
program Project1;
type
TFuncIntResult = reference to function: Integer;
// use function that returns anonymous method to avoid capturing the loop variable
function CreateFunc(i: Integer): TFuncIntResult;
begin
Result :=
function: Integer
begin
Result := i * i;
end;
end;
var
Funcs: array[0..9] of TFuncIntResult;
i: integer;
begin
// create 10 anonymous functions
for i := Low(Funcs) to High(Funcs) do
Funcs[i] := CreateFunc(i);
// call all 10 functions
for i := Low(Funcs) to High(Funcs) do
Writeln(Funcs[i]());
end.
- Output:
0 1 4 9 16 25 36 49 64 81
Dyalect
Dyalect captures variables by reference, therefore a way to achieve this is to capture a variable through a closure which in its turn returns a anonymous function like so:
var xs = []
let num = 10
for n in 0..<num {
xs.Add((n => () => n * n)(n))
}
for x in xs {
print(x())
}
- Output:
0 1 4 9 16 25 36 49 64 81
This is similar to a JavaScript (ES6) solution.
EchoLisp
(define (fgen i) (lambda () (* i i)))
(define fs (for/vector ((i 10)) (fgen i))) ;; vector of 10 anonymous functions
((vector-ref fs 5)) ;; calls fs[5]
→ 25
Elena
ELENA 6.x :
import system'routines;
import extensions;
public program()
{
var functions := Array.allocate(10).populate::(int i => { ^ i * i} );
functions.forEach::(func) { console.printLine(func()) }
}
- Output:
0 1 4 9 16 25 36 49 64 81
Elixir
funs = for i <- 0..9, do: (fn -> i*i end)
Enum.each(funs, &IO.puts &1.())
- Output:
0 1 4 9 16 25 36 49 64 81
Emacs Lisp
As of Emacs 24.3, lexical closures are supported, therefore alleviating hacks such as lexical-let.
;; -*- lexical-binding: t; -*-
(mapcar #'funcall
(mapcar (lambda (x)
(lambda ()
(* x x)))
'(1 2 3 4 5 6 7 8 9 10)))
;; => (1 4 9 16 25 36 49 64 81 100)
Erlang
Erlang uses lexical scoping and has anonymous functions.
-module(capture_demo).
-export([demo/0]).
demo() ->
Funs = lists:map(fun (X) ->
fun () ->
X * X
end
end,
lists:seq(1,10)),
lists:foreach(fun (F) ->
io:fwrite("~B~n",[F()])
end, Funs).
1> capture_demo:demo(). 1 4 9 16 25 36 49 64 81 100 ok
F#
Nearly identical to OCaml
[<EntryPoint>]
let main argv =
let fs = List.init 10 (fun i -> fun () -> i*i)
do List.iter (fun f -> printfn "%d" <| f()) fs
0
With List.map
[<EntryPoint>]
let main argv =
let fs = List.map (fun i -> fun () -> i*i) [0..9]
do List.iter (fun f -> printfn "%d" <| f()) fs
0
With List.mapi
[<EntryPoint>]
let main argv =
let fs = List.mapi (fun i x -> fun () -> i*i) (List.replicate 10 None)
do List.iter (fun f -> printfn "%d" <| f()) fs
0
With an infinite sequence
[<EntryPoint>]
let main argv =
let fs = Seq.initInfinite (fun i -> fun () -> i*i)
do Seq.iter (fun f -> printfn "%d" <| f()) (Seq.take 10 fs)
0
- Output:
0 1 4 9 16 25 36 49 64 81
Factor
Using lexical variables
USING: io kernel locals math prettyprint sequences ;
[let
! Create a sequence of 10 quotations
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
]
$ ./factor script.factor 3 squared is 9 8 squared is 64
The code :> i
always binds a new variable. This happens inside a loop, so this program creates 10 different bindings. Each closure [ i i * ]
captures a different binding, and remembers a different value.
The wrong way would use f :> i! 10 iota [ i! [ i i * ] ] map :> seq
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.
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
Fantom
class Closures
{
Void main ()
{
// define a list of functions, which take no arguments and return an Int
|->Int|[] functions := [,]
// create and store a function which returns i*i for i in 0 to 10
(0..10).each |Int i|
{
functions.add (|->Int| { i*i })
}
// show result of calling function at index position 7
echo ("Function at index: " + 7 + " outputs " + functions[7].call)
}
}
- Output:
Function at index: 7 outputs 49
Forth
: xt-array here { a }
10 cells allot 10 0 do
:noname i ]] literal dup * ; [[ a i cells + !
loop a ;
xt-array 5 cells + @ execute .
- Output:
25
FreeBASIC
FreeBASIC doesn't support closures or anonymous methods, as such. However, what we can do is to create an array of objects to capture their index and then call a method on those objects which squares the index. This approach is similar to how some other object oriented languages implement closures 'under the hood'.
' FB 1.05.0 Win64
Type Closure
Private:
index As Integer
Public:
Declare Constructor(index As Integer = 0)
Declare Function Square As Integer
End Type
Constructor Closure(index As Integer = 0)
This.index = index
End Constructor
Function Closure.Square As Integer
Return index * index
End Function
Dim a(1 To 10) As Closure
' create Closure objects which capture their index
For i As Integer = 1 To 10
a(i) = Closure(i)
Next
' call the Square method on all but the last object
For i As Integer = 1 to 9
Print a(i).Square
Next
Print
Print "Press any key to quit"
Sleep
- Output:
1 4 9 16 25 36 49 64 81
Free Pascal
FreePascal supports the same syntax als Delphi from version 3.3.1. It needs just a couple of defines.
program testthis;
{$mode objfpc}{$modeswitch functionreferences}{$modeswitch anonymousfunctions}
type
TFuncIntResult = reference to function: Integer;
// use function that returns anonymous method to avoid capturing the loop variable
function CreateFunc(i: Integer): TFuncIntResult;
begin
Result :=
function: Integer
begin
Result := i * i;
end;
end;
var
Funcs: array[0..9] of TFuncIntResult;
i: integer;
begin
// create 10 anonymous functions
for i := Low(Funcs) to High(Funcs) do
Funcs[i] := CreateFunc(i);
// call all 10 functions
for i := Low(Funcs) to High(Funcs) do
Writeln(Funcs[i]());
end.
- Output:
1 4 9 16 25 36 49 64 81
Go
package main
import "fmt"
func main() {
fs := make([]func() int, 10)
for i := range fs {
i := i
fs[i] = func() int {
return i * i
}
}
fmt.Println("func #0:", fs[0]())
fmt.Println("func #3:", fs[3]())
}
- Output:
func #0: 0 func #3: 9
You don't need to use this trick anymore in Go 1.22+:
package main
import "fmt"
func main() {
fs := make([]func() int, 10)
for i := range fs {
fs[i] = func() int {
return i * i
}
}
fmt.Println("func #0:", fs[0]())
fmt.Println("func #3:", fs[3]())
}
- Output:
func #0: 0 func #3: 9
If you take advantage of this, you should declare
go 1.22
in your go.mod file, so that older Go versions will not compile it. See this page for more information.
Groovy
Solution:
def closures = (0..9).collect{ i -> { -> i*i } }
Test:
assert closures instanceof List
assert closures.size() == 10
closures.each { assert it instanceof Closure }
println closures[7]()
- Output:
49
Haskell
Using map
:
fs = map (\i _ -> i * i) [1 .. 10]
Using list comprehensions:
fs = [const $ i * i | i <- [1 .. 10]]
Using infinite lists:
fs = take 10 coFs where coFs = [const $ i * i | i <- [1 ..]]
Testing:
> :t fs
fs :: [b -> Integer]
> map ($ ()) fs
[1,4,9,16,25,36,49,64,81,100]
> fs !! 9 $ ()
100
> fs !! 8 $ undefined
81
Icon and Unicon
This uses Unicon specific calling sequences for co-expressions. It can be made to run under Icon by modifying the calling syntax.
procedure main(args) # Closure/Variable Capture
every put(L := [], vcapture(1 to 10)) # build list of index closures
write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure
end
# The anonymous 'function', as a co-expression. Most of the code is standard
# boilerplate needed to use a co-expression as an anonymous function.
procedure vcapture(x) # vcapture closes over its argument
return makeProc { repeat { (x[1]^2) @ &source } }
end
procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package
return (@A[1], A[1])
end
package Utils provides makeProc Summary of Anonymous Functions in Unicon
- Output:
Randomly selecting L[8] = 64
Insitux
(var funcs (for x (range 11) #(* x x)))
[(0 funcs) ((3 funcs)) ((4 funcs))]
- Output:
[#(* x x) 9 16]
Io
blist := list(0,1,2,3,4,5,6,7,8,9) map(i,block(i,block(i*i)) call(i))
writeln(blist at(3) call) // prints 9
J
Explicit version
The natural way of implementing this in J is to define a function which produces a gerund of a constant function.
constF=:3 :0
{.''`(y "_)
)
Thus, a list of 10 functions each producing a value in 0..9, and another with their squares:
flist=: constF"0 i.10
slist=: constF"0 *:i.10
Referencing a function by its index (its position in that list):
flist @.3
3"_
slist @.3
9"_
Using a function, given its index:
flist @.4''
4
slist @.4''
16
Running a randomly picked function which is not the last one:
flist@.(?9) ''
7
slist@.(?9) ''
25
Using temporary locales
The problem statement "Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over" conflicts with the problem title "Value capture" in languages have sufficient abstraction to distinguish between value capture and variable and variable capture. This conflict even appears in J, and in general cases can require treatment of issues well outside the scope of this task.
Still, to address the task description, we should include a "variable capture" implementation, which in J could imply the use of "temporary locales" despite the fact that this approach would not satisfy the "simplest fashion possible" requirement.
For example, we could define an adverb 'geni' which takes a base function (which in this case will be *:
-- a function which squares an argument) and a value (which in this case will be an index), creates a locale where that value will be stored in a variable named i
and then returns an anonymous function which takes a reference to the locale (rather than the value) and extracts the value from the locale to generate the result.
We'll also use J's nuvoc {{
... }}
nesting definitional mechanism which implicitly determines the type of a definition instead of explicitly representing the definition types (1 :
, 2 :
, 3 :
, ...) which discourages nesting blocks.
geni=: {{
N=. cocreate''
i__N=. y
N
}}
task=: {{ u {{ u {{ u i__n [ y }} (geni y)`'' }}"0 i. y }}
This would be really bad form if we were intending to be useful, but - as described above - this approach is somewhat relevant to the task requirements.
Example use:
fns=: *: task 10
fns@.3 ''
9
fns@.5 ''
25
fns@.7 ''
49
Tacit (unorthodox) version
In J only adverbs and conjunctions (functionals) can produce verbs (functions)... Unless they are forced to cloak as verbs; in this instance, the rank conjunction (“) cloaks as a dyadic verb. (This does not work in recent versions of J as this takes advantage of a bug/feature where the interpreter does not produce a result with the correct shape):
( VL=. (<@:((<'"')(0:`)(,^:)&_))"0@:(^&2)@:i. 10 ) NB. Producing a list of boxed anonymous verbs (functions)
┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐
│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│
└───┴───┴───┴───┴────┴────┴────┴────┴────┴────┘
{::&VL 5 NB. Evoking the 6th verb (function)
25"_
{::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('')
25
Java
import java.util.function.Supplier;
import java.util.ArrayList;
public class ValueCapture {
public static void main(String[] args) {
ArrayList<Supplier<Integer>> funcs = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int j = i;
funcs.add(() -> j * j);
}
Supplier<Integer> foo = funcs.get(3);
System.out.println(foo.get()); // prints "9"
}
}
Alternative implementation that also
import java.util.List;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public interface ValueCapture {
public static void main(String... arguments) {
List<IntSupplier> closures = IntStream.rangeClosed(0, 10)
.<IntSupplier>mapToObj(i -> () -> i * i)
.collect(toList())
;
IntSupplier closure = closures.get(3);
System.out.println(closure.getAsInt()); // prints "9"
}
}
JavaScript
Imperative
var funcs = [];
for (var i = 0; i < 10; i++) {
funcs.push( (function(i) {
return function() { return i * i; }
})(i) );
}
window.alert(funcs[3]()); // alerts "9"
(Firefox 2+)
<script type="application/javascript;version=1.7">
var funcs = [];
for (var i = 0; i < 10; i++) {
let (i = i) {
funcs.push( function() { return i * i; } );
}
}
window.alert(funcs[3]()); // alerts "9"
</script>
"use strict";
let funcs = [];
for (let i = 0; i < 10; ++i) {
funcs.push((i => () => i*i)(i));
}
console.log(funcs[3]());
Functional
(function () {
'use strict';
// Int -> Int -> [Int]
function range(m, n) {
return Array.apply(null, Array(n - m + 1))
.map(function (x, i) {
return m + i;
});
}
var lstFns = range(0, 10)
.map(function (i) {
return function () {
return i * i;
};
})
return lstFns[3]();
})();
- Output:
9
let funcs = [...Array(10).keys()].map(i => () => i*i);
- Output:
console.log(funcs[3]()); 9
Julia
funcs = [ () -> i^2 for i = 1:10 ]
- Output:
julia> funcs[7]() 49
Kotlin
// version 1.0.6
fun main(args: Array<String>) {
// create an array of 10 anonymous functions which return the square of their index
val funcs = Array(10){ fun(): Int = it * it }
// call all but the last
(0 .. 8).forEach { println(funcs[it]()) }
}
- Output:
0 1 4 9 16 25 36 49 64
Lambdatalk
A translation from Javascript
{def A
{A.new
{S.map {lambda {:x} {* :x :x}}
{S.serie 0 10}
}}}
{A.get 3 {A}} // equivalent to A[3]
-> 9
{A.get 4 {A}}
-> 16
Latitude
Latitude is particularly well suited to this challenge, as the various iteration constructs actually take method arguments and call them multiple times. Thus, the loop variable is in fact an argument which is already closed over and distinct at each iteration.
functions := 10 times to (Array) map {
takes '[i].
proc { (i) * (i). }.
}.
functions visit { println: $1 call. }.
- Output:
0 1 4 9 16 25 36 49 64 81
LFE
Input at the REPL:
> (set funcs (list-comp ((<- m (lists:seq 1 10)))
(lambda () (math:pow m 2))))
Output:
(#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>)
Calling the functions:
> (funcall (car funcs))
1.0
> (funcall (cadr funcs))
4.0
> (funcall (cadddr funcs))
16.0
> (funcall (lists:nth 8 funcs))
64.0
Lingo
Lingo doesn't really support closures. But with the limitations described at Function composition and based on the fact that Lingo allows to create arbitrary code at runtime, the task can be solved like this:
-- parent script "CallFunction"
property _code
-- if the function is supposed to return something, the code must contain a line that starts with "res="
on new (me, code)
me._code = code
return me
end
on call (me)
----------------------------------------
-- If custom arguments were passed, evaluate them in the current context.
-- Note: in the code passed to the constructor they have to be referenced
-- as arg[1], arg[2], ...
arg = []
repeat with i = 3 to the paramCount
arg[i-2] = param(i)
end repeat
----------------------------------------
res = VOID
do(me._code)
return res
end
funcs = []
repeat with i = 1 to 10
code = "res="&i&"*"&i
funcs[i] = script("CallFunction").new(code)
end repeat
put call(funcs[3], _movie)
-- 9
Since the original task is a little trivial in terms of not depending on runtime arguments, here also a solution for an extended task: let each function[i] return the square of i plus the sum of all arguments passed to it at runtime:
funcs = []
repeat with i = 1 to 10
code = ""
put "res = "&i&"*"&i &RETURN after code
put "repeat with i = 1 to arg.count" &RETURN after code
put " res = res + arg[i]" &RETURN after code
put "end repeat" after code
funcs[i] = script("CallFunction").new(code)
end repeat
put call(funcs[3], _movie, 23)
-- 32
put call(funcs[7], _movie, 4, 5, 6)
-- 64
Logtalk
The example that follow uses Logtalk's native support for lambda expressions.
:- object(value_capture).
:- public(show/0).
show :-
integer::sequence(1, 10, List),
meta::map(create_closure, List, Closures),
meta::map(call_closure, List, Closures).
create_closure(Index, [Double]>>(Double is Index*Index)).
call_closure(Index, Closure) :-
call(Closure, Result),
write('Closure '), write(Index), write(' : '), write(Result), nl.
:- end_object.
- Output:
| ?- value_capture::show.
Closure 1 : 1
Closure 2 : 4
Closure 3 : 9
Closure 4 : 16
Closure 5 : 25
Closure 6 : 36
Closure 7 : 49
Closure 8 : 64
Closure 9 : 81
Closure 10 : 100
yes
Lua
funcs={}
for i=1,10 do
table.insert(funcs, function() return i*i end)
end
funcs[2]()
funcs[3]()
- Output:
4 9
M2000 Interpreter
Dim Base 0, A(10)
For i=0 to 9 {
a(i)=lambda i -> i**2
}
For i=0 to 9 {
Print a(i)()
}
0 1 4 9 16 25 36 49 64 81
Export list to clipboard
document a$
For i=0 to 9 {
a$=format$("{0:0:-20}",a(i)())+{
}
}
Clipboard a$
Using Inventory, and a stack object (reading from position, and another way, we pop functions, using Read)
Inventory Alfa
For i=0 to 9 {
Append Alfa, i:=lambda i -> i**2
}
For i=0 to 9 {
Print Alfa(i)()
}
Beta=Stack
Stack Beta {
For i=0 to 9 {
Data lambda i -> i**2
}
}
Def Fun(X)=X()
\\ reading functions from position 1 to 10
For i=0 to 9 {
Print fun(stackitem(Beta,i+1))
}
\\ pop functions form stack Beta
Stack Beta {
While not empty {
Read M
Print M()
}
}
Maple
> L := map( i -> (() -> i^2), [seq](1..10) ):
> seq( L[i](),i=1..10);
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
> L[4]();
16
Mathematica / Wolfram Language
Function[i, i^2 &] /@ Range@10
->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &}
%[[2]][]
->4
Nemerle
using System.Console;
module Closures
{
Main() : void
{
def f(x) { fun() { x ** 2 } }
def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing
WriteLine($"$(funcs[4]())");
WriteLine($"$(funcs[2]())");
}
}
- Output:
16 4
Nim
var funcs: seq[proc(): int] = @[]
for i in 0..9:
(proc =
let x = i
funcs.add(proc (): int = x * x))()
for i in 0..8:
echo "func[", i, "]: ", funcs[i]()
Objeck
use Collection.Generic;
class Capture {
function : Main(args : String[]) ~ Nil {
funcs := Vector->New()<FuncHolder<IntHolder> >;
for(i := 0; i < 10; i += 1;) {
funcs->AddBack(FuncHolder->New(\() ~ IntHolder : () => i * i)<IntHolder>);
};
each(i : funcs) {
func := funcs->Get(i)->Get()<IntHolder>;
func()->Get()->PrintLine();
};
}
}
- Output:
0 1 4 9 16 25 36 49 64 81
Objective-C
with ARC
NSMutableArray *funcs = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
[funcs addObject:[^ { return i * i; } copy]];
}
int (^foo)(void) = funcs[3];
NSLog(@"%d", foo()); // logs "9"
OCaml
All functions in OCaml are closures.
let () =
let cls = Array.init 10 (fun i -> (function () -> i * i)) in
Random.self_init ();
for i = 1 to 6 do
let x = Random.int 9 in
Printf.printf " fun.(%d) = %d\n" x (cls.(x) ());
done
- Output:
fun.(4) = 16 fun.(1) = 1 fun.(4) = 16 fun.(7) = 49 fun.(3) = 9 fun.(6) = 36
Oforth
: newClosure(i) #[ i sq ] ;
10 seq map(#newClosure) at(7) perform .
- Output:
49
PARI/GP
vector(10,i,()->i^2)[5]()
- Output:
%1 = 25
Perl
my @f = map(sub { $_ * $_ }, 0 .. 9); # @f is an array of subs
print $f[$_](), "\n" for (0 .. 8); # call and print all but last
- Output:
0 1 4 9 16 25 36 49 64
Phix
Phix does not support closures, but they seem easy enough to emulate
with javascript_semantics -- First some generic handling stuff, handles partial_args -- of any mixture of any length and element types. sequence closures = {} function add_closure(integer rid, sequence partial_args) closures = append(closures,{rid,partial_args}) return length(closures) -- (return an integer id) end function function call_closure(integer id, sequence args) {integer rid, sequence partial_args} = closures[id] return call_func(rid,partial_args&args) end function -- The test routine to be made into a closure, or ten -- Note that all external references/captured variables must -- be passed as arguments, and grouped together on the lhs function square(integer i) return i*i end function -- Create the ten closures as asked for. -- Here, cids is just {1,2,3,4,5,6,7,8,9,10}, however ids would be more -- useful for a mixed bag of closures, possibly stored all over the shop. -- Likewise add_closure could have been a procedure for this demo, but -- you would probably want the function in a real-world application. sequence cids = {} for i=1 to 10 do --for i=11 to 20 do -- alternative test cids &= add_closure(routine_id("square"),{i}) end for -- And finally call em (this loop is blissfully unaware what function -- it is actually calling, and what partial_arguments it is passing) for i=1 to 10 do printf(1," %d",call_closure(cids[i],{})) end for
- Output:
1 4 9 16 25 36 49 64 81 100
output if that 11 to 20 add_closure loop is used instead:
121 144 169 196 225 256 289 324 361 400
Note however that any captured values are effectively immutable, unless you also pass the id to the closure, and that in turn does rude things to closures[id][2].
A dictionary based approach may prove somewhat easier:
with javascript_semantics function square(integer tid) integer i = getd("i",tid) -- (setd valid here too) return i*i end function sequence tids = {} for i=1 to 10 do --for i=11 to 20 do tids &= new_dict({{"i",i}}) end for for i=1 to 10 do printf(1," %d",square(tids[i])) end for
same output, for both tests
Phixmonti
def power2
dup *
enddef
getid power2 10 repeat
len for
dup rot swap get rot swap exec print " " print
endfor
nl
/# Another mode #/
len for
var i
i get i swap exec print " " print
endfor
PHP
<?php
$funcs = array();
for ($i = 0; $i < 10; $i++) {
$funcs[] = function () use ($i) { return $i * $i; };
}
echo $funcs[3](), "\n"; // prints 9
?>
This method can capture value types like numbers, strings, arrays, etc., but not objects.
<?php
$funcs = array();
for ($i = 0; $i < 10; $i++) {
$funcs[] = create_function('', '$i = ' . var_export($i, true) . '; return $i * $i;');
}
echo $funcs[3](), "\n"; // prints 9
?>
PicoLisp
(setq FunList
(make
(for @N 10
(link (curry (@N) () (* @N @N))) ) ) )
Test:
: ((get FunList 2)) -> 4 : ((get FunList 8)) -> 64
Pike
array funcs = ({});
foreach(enumerate(10);; int i)
{
funcs+= ({
lambda(int j)
{
return lambda()
{
return j*j;
};
}(i)
});
}
PowerShell
I'm not sure that I understood the question/task. This task seems to be the same as the 'Accumulator Factory' task.
function Get-Closure ([double]$Number)
{
{param([double]$Sum) return $script:Number *= $Sum}.GetNewClosure()
}
for ($i = 1; $i -lt 11; $i++)
{
$total = Get-Closure -Number $i
[PSCustomObject]@{
Function = $i
Sum = & $total -Sum $i
}
}
- Output:
Function Sum -------- --- 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100
$numbers = 1..20 | Get-Random -Count 10
foreach ($number in $numbers)
{
$total = Get-Closure -Number $number
[PSCustomObject]@{
Function = $number
Sum = & $total -Sum $number
}
}
- Output:
Function Sum -------- --- 4 16 16 256 3 9 17 289 9 81 15 225 7 49 6 36 1 1 20 400
Prolog
Works with SWI-Prolog and module lambda.pl from Ulrich Neumerkel.
lambda.pl can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
:-use_module(library(lambda)).
closure :-
numlist(1,10, Lnum),
maplist(make_func, Lnum, Lfunc),
maplist(call_func, Lnum, Lfunc).
make_func(I, \X^(X is I*I)).
call_func(N, F) :-
call(F, R),
format('Func ~w : ~w~n', [N, R]).
- Output:
?- closure. Func 1 : 1 Func 2 : 4 Func 3 : 9 Func 4 : 16 Func 5 : 25 Func 6 : 36 Func 7 : 49 Func 8 : 64 Func 9 : 81 Func 10 : 100 true.
Python
The naive way does not work:
funcs = []
for i in range(10):
funcs.append(lambda: i * i)
print funcs[3]() # prints 81
The simplest solution is to add optional parameters with default arguments at the end of the parameter list, to create a local copy of the variable, and evaluate the variable at the time the function is created. (The optional parameter is not expected to ever be passed.) Often, the optional parameter will be named the same as the variable to be closed over (leading to odd-looking code of the form foo=foo
in the arguments), so that the code inside the function need not be changed, but this might lead to confusion. This technique does not work for functions with a variable number of arguments.
funcs = []
for i in range(10):
funcs.append(lambda i=i: i * i)
print funcs[3]() # prints 9
or equivalently the list comprehension:
funcs = [lambda i=i: i * i for i in range(10)]
print funcs[3]() # prints 9
Another solution is to wrap an immediately-executed function around our function. The wrapping function creates a new scope, and its execution forces the evaluation of the variable to be closed over.
funcs = []
for i in range(10):
funcs.append((lambda i: lambda: i * i)(i))
print funcs[3]() # prints 9
or equivalently the list comprehension:
funcs = [(lambda i: lambda: i)(i * i) for i in range(10)]
print funcs[3]() # prints 9
In this case it is also possible to use map()
since the function passed to it creates a new scope
funcs = map(lambda i: lambda: i * i, range(10))
print funcs[3]() # prints 9
It is also possible to use eval
.
funcs=[eval("lambda:%s"%i**2)for i in range(10)]
print funcs[3]() # prints 9
Quackery
Strictly speaking, we could get away with [ table 0 1 4 9 16 25 36 49 64 81 ] is functions ( n --> n )
for this task, as numbers in Quackery are functions that return their own value when executed, e.g 5 do
returns 5
, but it feels like cheating.
[ table ] is functions ( n --> [ )
10 times
[ i^ ' [ dup * ] join
' functions put ]
5 functions do echo
- Output:
25
R
R is a natural language for this task, but you need to understand the nuances of delayed evaluation. Arguments in R are referred to as promises because they aren't evaluated until first use. If you're not careful, you can bind to a promise that hasn't yet been evaluated, and you won't get what you expect.
# assign 's' a list of ten functions
s <- sapply (1:10, # integers 1..10 become argument 'x' below
function (x) {
x # force evaluation of promise x
function (i=x) i*i # this *function* is the return value
})
s[[5]]() # call the fifth function in the list of returned functions
[1] 25 # returns vector of length 1 with the value 25
Note that I bound the captured variable as the default argument on a unary function. If you supply your own argument, as below, it squares the supplied argument and ignores the default argument.
s[[5]](10)
[1] 100
As a further technicality, note that you need some extra voodoo to modify the bound argument with persistence across calls. This example increments the bound variable after each call.
s <- sapply (1:10,
function (x) {
x # force evaluation of promise x
function () {
R <- x*x
# evaluate the language expression "x <- x + 1" in the persistent parent environment
evalq (x <- x + 1, parent.env(environment()))
R # return squared value
}})
s[[5]]()
[1] 25 # 5^2
s[[5]]()
[1] 36 # now 6^2
s[[1]]()
[1] 1 # 1^2
s[[1]]()
[1] 4 # now 2^2
As shown, each instance increments separately.
--- Edit ---
I think that modifying the bound variable can be done in a simpler way. Instead of:
evalq (x <- x + 1, parent.env(environment()))
substitute:
x <<- x + 1
Testing:
> s[[5]]() [1] 25 > s[[5]]() [1] 36 > s[[5]]() [1] 49 > s[[2]]() [1] 4 > s[[2]]() [1] 9 > s[[2]]() [1] 16
Racket
#lang racket
(define functions (for/list ([i 10]) (λ() (* i i))))
(map (λ(f) (f)) functions)
- Output:
'(0 1 4 9 16 25 36 49 64 81)
Raku
(formerly Perl 6)
All blocks are anonymous closures in Raku, and parameters are lexicals, so it's easy to generate a list of them. We'll use a gather/take generator loop, and call the closures in random order, just to keep things interesting.
my @c = gather for ^10 -> $i {
take { $i * $i }
}
.().say for @c.pick(*); # call them in random order
- Output:
36 64 25 1 16 0 4 9 81 49
Or equivalently, using a more functional notation:
say .() for pick *, map -> $i { -> {$i * $i} }, ^10
Red
funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]]
>> funs/7
== 49
REXX
This REXX version supports both a one─ and zero─based list (it can be specified at the command line.)
The default is to use a zero─based list.
The list can also be specified at the command line. The default is an ordered list based on an obscure sequence (but puzzle enthusiasts can figure it out).
No error checking is performed on the user input(s).
/*REXX program has a list of ten functions, each returns its invocation (index) squared.*/
parse arg seed base $ /*obtain optional arguments from the CL*/
if datatype(seed, 'W') then call random ,,seed /*Not given? Use random start seed. */
if base=='' | base="," then base=0 /* " " Use a zero─based list. */
if $='' then $= 8 5 4 9 1 3 2 7 6 0 /* " " Use ordered function list*/
/*the $ list must contain 10 functions.*/
say 'the' word("zero one", base+1)'─based list is: ' $ /*show list of functions.*/
/*BASED must be either 1 or 0. */
?='.'random(0, 9) /*get a random name of a function. */
interpret 'CALL' ? /*invoke a randomly selected function. */
say 'function ' ? " returned " result /*display the value of random function.*/
exit /*stick a fork in it, we're all done. */
/*────────────────────────[Below are the closest things to anonymous functions in REXX].*/
.0: return .(0) /*function .0 ─── bump its counter. */
.1: return .(1) /* ' .1 " " " " */
.2: return .(2) /* ' .2 " " " " */
.3: return .(3) /* ' .3 " " " " */
.4: return .(4) /* ' .4 " " " " */
.5: return .(5) /* ' .5 " " " " */
.6: return .(6) /* ' .6 " " " " */
.7: return .(7) /* ' .7 " " " " */
.8: return .(8) /* ' .8 " " " " */
.9: return .(9) /* ' .9 " " " " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.: arg #; _=wordpos(#,$); if _==0 then return 'not in the list.'; return (_-(\base))**2
- output when using the default input which assume a zero─based list):
the zero─based list is: 8 5 4 9 1 3 2 7 6 0 function .0 returned 81
- output when using the input of: , 1
the one─based list is: 8 5 4 9 1 3 2 7 6 0 function .0 returned 100
Ring
x = funcs(7)
see x + nl
func funcs n
fn = list(n)
for i = 1 to n
fn[i] =i*i
next
return fn
Output:
1 4 9 16 25 36 49
Ruby
procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda
p procs[7].call # => 49
In Ruby, lambdas (and procs) are closures.
Rust
One note here about referencing values and capturing values:
Rust employs strong ownership rules that do not allow mutating a value that is referenced (pointed to without allowing mutation) from elsewhere. It also doesn't allow referencing a value that may be dropped before the reference is released. The proof that we really did capture the value is therefore unnecessary. Either we did or it wouldn't have compiled.
fn main() {
let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect();
println!("7th val: {}", fs[7]());
}
- Output:
7th val: 49
Scala
val closures=for(i <- 0 to 9) yield (()=>i*i)
0 to 8 foreach (i=> println(closures(i)()))
println("---\n"+closures(7)())
- Output:
0 1 4 9 16 25 36 49 64 --- 49
Scheme
;;; Collecting lambdas in a tail-recursive function.
(define (build-list-of-functions n i list)
(if (< i n)
(build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list))
list))
(define list-of-functions (build-list-of-functions 10 1 '()))
(map (lambda (f) (f)) list-of-functions)
((list-ref list-of-functions 8))
- Output:
'(1 4 9 16 25 36 49 64 81)
81
Using Scheme SRFI 1 iota procedure can be simplified to:
(define list-of-functions (map (lambda (x) (lambda () (* x x))) (iota 0 1 10)))
; print the result
(display
(map (lambda (n) (n)) list-of-functions)
(newline)
Sidef
var f = (
10.of {|i| func(j){i * j} }
)
9.times { |j|
say f[j](j)
}
- Output:
0 1 4 9 16 25 36 49 64
Starting from i=1:
var f = (1..10).map { |i|
func(j){i * j}
}
for j (1..9) {
say f[j-1](j)
}
- Output:
1 4 9 16 25 36 49 64 81
Smalltalk
funcs := (1 to: 10) collect: [ :i | [ i * i ] ] .
(funcs at: 3) value displayNl .
- Output:
9
Sparkling
In Sparkling, upvalues (variables in the closure) are captured by value.
var fnlist = {};
for var i = 0; i < 10; i++ {
fnlist[i] = function() {
return i * i;
};
}
print(fnlist[3]()); // prints 9
print(fnlist[5]()); // prints 25
Alternately:
var fnlist = map(range(10), function(k, v) {
return function() {
return v * v;
};
});
print(fnlist[3]()); // prints 9
print(fnlist[5]()); // prints 25
Standard ML
List.map (fn x => x () ) ( List.tabulate (10,(fn i => (fn ()=> i*i)) ) ) ;
Output:
val it = [0,1,4,9,16,25,36,49,64,81] : int list
Swift
By default, Swift captures variables by reference. A naive implementation like the following C-style for loop does not work:
var funcs: [() -> Int] = []
for var i = 0; i < 10; i++ {
funcs.append({ i * i })
}
println(funcs[3]()) // prints 100
However, using a for-in loop over a range does work, since you get a new constant at every iteration:
var funcs: [() -> Int] = []
for i in 0..<10 {
funcs.append({ i * i })
}
println(funcs[3]()) // prints 9
The C-style for loop can also work if we explicitly capture the loop counter:
var funcs: [() -> Int] = []
for var i = 0; i < 10; i++ {
funcs.append({ [i] in i * i })
}
println(funcs[3]()) // prints 9
Alternately, we can also use map()
to map over a range, and create the squaring closure inside the mapping closure which has the integer as a parameter:
let funcs = [] + map(0..<10) {i in { i * i }}
println(funcs[3]()) // prints 9
Tcl
Tcl does not support closures (either value-capturing or variable-capturing) by default, but value-capturing closures are easy to emulate.
package require Tcl 8.6; # Just for tailcall command
# Builds a value-capturing closure; does NOT couple variables
proc closure {script} {
set valuemap {}
foreach v [uplevel 1 {info vars}] {
lappend valuemap [list $v [uplevel 1 [list set $v]]]
}
set body [list $valuemap $script [uplevel 1 {namespace current}]]
# Wrap, to stop untoward argument passing
return [list apply [list {} [list tailcall apply $body]]]
# A version of the previous line compatible with Tcl 8.5 would be this
# code, but the closure generated is more fragile:
### return [list apply $body]
}
# Simple helper, to avoid capturing unwanted variable
proc collectFor {var from to body} {
upvar 1 $var v
set result {}
for {set v $from} {$v < $to} {incr v} {lappend result [uplevel 1 $body]}
return $result
}
# Build a list of closures
proc buildList {} {
collectFor i 0 10 {
closure {
# This is the body of the closure
return [expr $i*$i]
}
}
}
set theClosures [buildList]
foreach i {a b c d e} {# Do 5 times; demonstrates no variable leakage
set idx [expr {int(rand()*9)}]; # pick random int from [0..9)
puts $idx=>[{*}[lindex $theClosures $idx]]
}
- Output:
5=>25 0=>0 8=>64 1=>1 8=>64
TXR
Sugared
(let ((funs (mapcar (ret (op * @@1 @@1)) (range 1 10))))
[mapcar call [funs 0..-1]])
- Output:
(1 4 9 16 25 36 49 64 81)
Desugared
The explicit lambda
structure here is much like the implicit ones in the "Sugared" example:
;; Dropping distracting "skip last" requirement
;; (not implemented in original Elisp either).
(mapcar 'call
(mapcar (lambda ()
(lambda () (* x x))) '(1 2 3 4 5 6 7 8 9 10)))
Delimited Continuations
In this interactive example, we capture delimited continuations inside a simple for
loop. Because the variable binding environment is not necessarily in the stack which is captured, we rebind the loop variable.
This is the TXR Lisp interactive listener of TXR 124. Use the :quit command or type Ctrl-D on empty line to exit. 1> (let ((conts)) (for ((i 0)) ((< i 10) (nreverse conts)) ((inc i)) (let ((cap i)) (push (block sqr (suspend sqr f (op f nil)) (* cap cap)) conts)))) (#<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112> #<interpreted fun: lambda #:rest-0112>) 2> (call (first *1)) 0 3> (call (second *1)) 1 4> (call (fifth *1)) 16 5> (call [*1 4]) 16 6> (call [*1 7]) 49
The suspend
operator suspends the execution of the sqr
block, causing it to return the function (op f nil)
. The variable f
represents the captured continuation as a function. Continuation functions take one mandatory argument. We don't need that here, hence the (op f nil)
expression is returned: it curries the one arg continuation function f
to a function with no arguments.
The loop pushes these suspended continuations into a list, and then nreverse
-s it.
We then interactively call the continuations in the list.
Whenever we call a continuation, the (block sqr ...)
environment is restored. and the suspended computation inside the block resumes by returning out of the (suspend ...)
form normally. The block then executes to completion, returning the (* cap cap)
form's value. At that point, our call to the continuation terminates, yielding that value.
Wren
var fs = List.filled(10, null)
for (i in 0...fs.count) {
fs[i] = Fn.new { i * i }
}
for (i in 0...fs.count-1) System.print("Function #%(i): %(fs[i].call())")
- Output:
Function #0: 0 Function #1: 1 Function #2: 4 Function #3: 9 Function #4: 16 Function #5: 25 Function #6: 36 Function #7: 49 Function #8: 64
Yabasic
dim funcs$(10)
sub power2(i)
return i * i
end sub
for i = 1 to 10
funcs$(i) = "power2"
next
for i = 1 to 10
print execute(funcs$(i), i)
next
zkl
Create a closure of the index over a square function
(0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64
list:=(0).pump(10,List,fcn(i){i*i}.fp);
foreach n in (list.len()-1) { list[n]().println() }
list.run(True).println()
- Output:
0 1 4 9 16 25 36 49 64 L(0,1,4,9,16,25,36,49,64,81)
- Functions and subroutines
- Programming Tasks
- Solutions by Programming Task
- 11l
- Acornsoft Lisp
- Ada
- ALGOL 68
- AntLang
- AppleScript
- Arturo
- Axiom
- Babel
- Bracmat
- C
- C sharp
- C++
- Ceylon
- Clojure
- CoffeeScript
- Common Lisp
- D
- Delphi
- Dyalect
- EchoLisp
- Elena
- Elixir
- Emacs Lisp
- Erlang
- F Sharp
- Factor
- Fantom
- Forth
- FreeBASIC
- Free Pascal
- Go
- Groovy
- Haskell
- Icon
- Unicon
- Unicon Code Library
- Insitux
- Io
- J
- Java
- JavaScript
- Julia
- Kotlin
- Lambdatalk
- Latitude
- LFE
- Lingo
- Logtalk
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- Nemerle
- Nim
- Objeck
- Objective-C
- OCaml
- Oforth
- PARI/GP
- Perl
- Phix
- Phixmonti
- PHP
- PicoLisp
- Pike
- PowerShell
- Prolog
- Python
- Quackery
- R
- Racket
- Raku
- Red
- REXX
- Ring
- Ruby
- Rust
- Scala
- Scheme
- Sidef
- Smalltalk
- Sparkling
- Standard ML
- Swift
- Tcl
- TXR
- Wren
- Yabasic
- Zkl
- BASIC/Omit
- Brlcad/Omit
- GUISS/Omit
- Locomotive Basic/Omit
- PureBasic/Omit
- ZX Spectrum Basic/Omit
- Pages with too many expensive parser function calls