Closures/Value capture: Difference between revisions
m
→=Using temporary locales
Alextretyak (talk | contribs) (Added 11l) |
|||
(20 intermediate revisions by 12 users not shown) | |||
Line 1:
[[Category:Functions and subroutines]]
{{task}}
Line 15 ⟶ 16:
See also: [[Multiple distinct objects]]
=={{header|11l}}==
<
L(i) 10
funcs.append(() -> @=i * @=i)
print(funcs[3]())</syntaxhighlight>
{{out}}
Line 28 ⟶ 26:
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}}==
Line 33 ⟶ 93:
One way to realize closures in Ada is the usage of protected objects.
<
procedure Value_Capture is
Line 62 ⟶ 122:
Ada.Text_IO.Put(Integer'Image(A(I).Result));
end loop;
end Value_Capture;</
{{out}}
<pre> 1 4 9 16 25 36 49 64 81</pre>
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|2.8}}
<
[1:10]PROC(BOOL)INT squares;
Line 83 ⟶ 142:
FOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD
</syntaxhighlight>
{{out}}
<pre>
Line 91 ⟶ 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.
=={{header|AntLang}}==
<
(8 elem fns)[]</
=={{header|AppleScript}}==
{{trans|JavaScript}}
<
set fns to {}
Line 114 ⟶ 171:
end |λ|
end script
end closure</
{{Out}}
<pre>9</pre>
Line 120 ⟶ 177:
Or, in a more functional pattern of composition:
<
script closure
Line 173 ⟶ 230:
end script
end if
end mReturn</
{{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}}==
Using the Spad compiler:
<
TestPackage() : with
test: () -> List((()->Integer))
== add
test() == [(() +-> i^2) for i in 1..10]</
This can be called from the interpreter using:
<
{{out}}
<
Type: List(Integer)</
=={{header|Babel}}==
<
{ iter
1 take bons 1 take
Line 203 ⟶ 273:
10 times
collect !
{eval %d nl <<} each }))</
{{out}}
<
81
64
Line 215 ⟶ 285:
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.
=={{header|Bracmat}}==
<
& :?funcs
& whl
Line 229 ⟶ 298:
& whl'(!funcs:%?func %?funcs&out$(!func$))
);
</syntaxhighlight>
{{out}}
<pre>0
Line 240 ⟶ 309:
49
64</pre>
=={{header|C}}==
Line 247 ⟶ 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.
<
#include <string.h>
#include <stdlib.h>
Line 287 ⟶ 355:
return 0;
}</
{{out}}
<syntaxhighlight lang="text">func[0]: 0
func[1]: 1
func[2]: 4
Line 297 ⟶ 365:
func[6]: 36
func[7]: 49
func[8]: 64</
===Greenspunned mini Lisp dialect===
Line 303 ⟶ 371:
See [[Closures/Variable_capture/C]] for complete code. The relevant excerpt is:
<
{
t = intern(lit("t"));
Line 335 ⟶ 403:
}
return 0;
}</
Here, we create an environment explicitly as an association list
Line 355 ⟶ 423:
0
</pre>
=={{header|C sharp|C#}}==
===Using Linq===
<
using System.Linq;
Line 372 ⟶ 439:
}
}
}</
{{out}}
<syntaxhighlight lang="text">0
1
4
Line 382 ⟶ 449:
36
49
64</
===Using delegates only===
<
using System;
using System.Collections.Generic;
Line 409 ⟶ 476:
}
}
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">0
1
4
Line 419 ⟶ 486:
36
49
64</
=={{header|C++}}==
{{works with|C++11}}
<
#include <functional>
#include <vector>
Line 434 ⟶ 500:
std::cout << f( ) << std::endl ;
return 0;
}</
{{out}}
<pre>0
Line 447 ⟶ 513:
81
</pre>
=={{header|Ceylon}}==
<
//create a list of closures with a list comprehension
Line 457 ⟶ 522:
print("closure number ``i`` returns: ``closure()``");
}
}</
=={{header|Clojure}}==
<
(printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))</
{{Out}}
<pre>9
16</pre>
=={{header|CoffeeScript}}==
<
# Generate an array of functions.
funcs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i )
Line 474 ⟶ 537:
# Call each function to demonstrate value capture.
console.log func() for func in funcs
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(loop for i from 1 to 10
collect (cons i (let ((i i))
Line 485 ⟶ 547:
4
CL-USER> (funcall (cdr (assoc 8 alist)))
64</
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}}==
===Less Functional Version===
<
void main() {
Line 500 ⟶ 561:
writeln(funcs[3]());
}</
{{out}}
<pre>9</pre>
===More Functional Version===
<
import std.stdio, std.range, std.algorithm;
10.iota.map!(i => () => i ^^ 2).map!q{ a() }.writeln;
}</
{{out}}
<pre>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</pre>
=={{header|Delphi}}==
{{works with|Delphi 2009}}
<
type
Line 540 ⟶ 600:
for i := Low(Funcs) to High(Funcs) do
Writeln(Funcs[i]());
end.</
{{out}}
<pre>0
Line 553 ⟶ 613:
81
</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:
<
let num = 10
for n in 0..<num {
xs.
}
for x in xs {
print(x())
}</
{{out}}
Line 582 ⟶ 641:
This is similar to a JavaScript (ES6) solution.
=={{header|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
</syntaxhighlight>
=={{header|Elena}}==
ELENA
<
import extensions;
public program()
{
var functions := Array.allocate(10).populate::(int i => { ^ i * i} );
functions.forEach::(func) { console.printLine(func()) }
}</
{{out}}
<pre>0
Line 615 ⟶ 672:
=={{header|Elixir}}==
<
Enum.each(funs, &IO.puts &1.())</
{{out}}
Line 631 ⟶ 688:
81
</pre>
=={{header|Emacs Lisp}}==
As of Emacs 24.3, lexical closures are supported, therefore alleviating hacks such as lexical-let.
<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}}==
Erlang uses lexical scoping and has anonymous functions.
<
-module(capture_demo).
-export([demo/0]).
Line 659 ⟶ 714:
io:fwrite("~B~n",[F()])
end, Funs).
</syntaxhighlight>
<pre>
1> capture_demo:demo().
Line 674 ⟶ 729:
ok
</pre>
=={{header|F_Sharp|F#}}==
Nearly identical to OCaml
<
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
<
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
<
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
<
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</
{{out}}
Line 717 ⟶ 771:
81
</pre>
=={{header|Factor}}==
===Using lexical variables===
<
[let
Line 733 ⟶ 786:
seq nth call .
] each
]</
<pre>$ ./factor script.factor
Line 746 ⟶ 799:
Forget the variable! Each ''fried quotation'' captures some values by pulling them from the stack.
<
! Push a sequence of 10 quotations
Line 757 ⟶ 810:
over nth call .
] each
drop</
=={{header|Fantom}}==
<
class Closures
{
Line 779 ⟶ 831:
}
}
</syntaxhighlight>
{{out}}
Line 785 ⟶ 837:
Function at index: 7 outputs 49
</pre>
=={{header|Forth}}==
<
10 cells allot 10 0 do
:noname i ]] literal dup * ; [[ a i cells + !
loop a ;
xt-array 5 cells + @ execute .</
{{out}}
<syntaxhighlight lang
=={{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'.
<
Type Closure
Line 834 ⟶ 884:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 848 ⟶ 898:
81
</pre>
=={{header|Go}}==
<
import "fmt"
Line 864 ⟶ 913:
fmt.Println("func #0:", fs[0]())
fmt.Println("func #3:", fs[3]())
}</
{{out}}
<pre>
Line 870 ⟶ 919:
func #3: 9
</pre>
=={{header|Groovy}}==
Solution:
<
Test:
<
assert closures.size() == 10
closures.each { assert it instanceof Closure }
println closures[7]()</
{{out}}
<pre>49</pre>
=={{header|Haskell}}==
Using <code>map</code>:
<
Using list comprehensions:
<
Using infinite lists:
<
Testing:
<
fs :: [b -> Integer]
> map ($ ()) fs
Line 907 ⟶ 954:
100
> fs !! 8 $ undefined
81</
=={{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.
<
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
Line 926 ⟶ 972:
procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package
return (@A[1], A[1])
end</
{{libheader|Unicon Code Library}}
Line 936 ⟶ 982:
<pre>Randomly selecting L[8] = 64</pre>
=={{
<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}}==
Line 946 ⟶ 1,005:
The natural way of implementing this in J is to define a function which produces a gerund of a constant function.
<
{.''`(y "_)
)</
Thus, a list of 10 functions each producing a value in 0..9, and another with their squares:
<
slist=: constF"0 *:i.10</
Referencing a function by its index (its position in that list):
<
3"_
slist @.3
9"_</
Using a function, given its index:
<
4
slist @.4''
16</
Running a randomly picked function which is not the last one:
<
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 [[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===
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. (
<
┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐
│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│
Line 987 ⟶ 1,078:
25"_
{::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('')
25</
=={{header|Java}}==
{{works with|Java|8+}}
<
import java.util.ArrayList;
Line 1,005 ⟶ 1,096:
System.out.println(foo.get()); // prints "9"
}
}</
Alternative implementation that also {{works with|Java|8+}}
<
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
Line 1,024 ⟶ 1,115:
System.out.println(closure.getAsInt()); // prints "9"
}
}</
=={{header|JavaScript}}==
===Imperative===
<
for (var i = 0; i < 10; i++) {
funcs.push( (function(i) {
Line 1,036 ⟶ 1,126:
})(i) );
}
window.alert(funcs[3]()); // alerts "9"</
{{works with|JavaScript|1.7+}} (Firefox 2+)
<
var funcs = [];
for (var i = 0; i < 10; i++) {
Line 1,047 ⟶ 1,137:
}
window.alert(funcs[3]()); // alerts "9"
</script></
{{works with|JavaScript|ES6}}
<
let funcs = [];
for (let i = 0; i < 10; ++i) {
funcs.push((i => () => i*i)(i));
}
console.log(funcs[3]());</
===Functional ===
Line 1,061 ⟶ 1,151:
{{works with|JavaScript|ES5}}
<
'use strict';
Line 1,081 ⟶ 1,171:
return lstFns[3]();
})();</
{{out}}
Line 1,089 ⟶ 1,179:
{{works with|JavaScript|ES6}}
<
{{out}}
<pre>
Line 1,095 ⟶ 1,185:
9
</pre>
=={{header|Julia}}==
<
{{out}}
<pre>
Line 1,103 ⟶ 1,192:
49
</pre>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,112 ⟶ 1,200:
// call all but the last
(0 .. 8).forEach { println(funcs[it]()) }
}</
{{out}}
Line 1,126 ⟶ 1,214:
64
</pre>
=={{header|Lambdatalk}}==
A translation from Javascript
<
{def A
{A.new
Line 1,141 ⟶ 1,228:
{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.
<
takes '[i].
proc { (i) * (i). }.
}.
functions visit { println: $1 call. }.</
{{Out}}
Line 1,165 ⟶ 1,251:
64
81</pre>
=={{header|LFE}}==
Input at the REPL:
<
> (set funcs (list-comp ((<- m (lists:seq 1 10)))
(lambda () (math:pow m 2))))
</syntaxhighlight>
Output:
<
(#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>
Line 1,181 ⟶ 1,266:
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>
#Fun<lfe_eval.23.101079464> #Fun<lfe_eval.23.101079464>)
</syntaxhighlight>
Calling the functions:
<
> (funcall (car funcs))
1.0
Line 1,194 ⟶ 1,279:
64.0
</syntaxhighlight>
=={{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:
<
property _code
Line 1,223 ⟶ 1,307:
do(me._code)
return res
end</
<
repeat with i = 1 to 10
code = "res="&i&"*"&i
Line 1,232 ⟶ 1,316:
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:
<
repeat with i = 1 to 10
code = ""
Line 1,250 ⟶ 1,334:
put call(funcs[7], _movie, 4, 5, 6)
-- 64</
=={{header|Logtalk}}==
The example that follow uses Logtalk's native support for lambda expressions.
<
:- object(value_capture).
Line 1,270 ⟶ 1,353:
:- end_object.
</syntaxhighlight>
{{out}}
<
| ?- value_capture::show.
Closure 1 : 1
Line 1,285 ⟶ 1,368:
Closure 10 : 100
yes
</syntaxhighlight>
=={{header|Lua}}==
<
funcs={}
for i=1,10 do
Line 1,295 ⟶ 1,377:
funcs[2]()
funcs[3]()
</syntaxhighlight>
{{out}}
<pre>4
9
</pre>
=={{header|M2000 Interpreter}}==
<
Dim Base 0, A(10)
For i=0 to 9 {
Line 1,310 ⟶ 1,391:
Print a(i)()
}
</syntaxhighlight>
Print
0
Line 1,324 ⟶ 1,405:
Export list to clipboard
<
document a$
For i=0 to 9 {
Line 1,331 ⟶ 1,412:
}
Clipboard a$
</syntaxhighlight>
Using Inventory, and a stack object (reading from position, and another way, we pop functions, using Read)
<
Inventory Alfa
For i=0 to 9 {
Line 1,364 ⟶ 1,445:
}
</syntaxhighlight>
=={{header|Maple}}==
<
> seq( L[i](),i=1..10);
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
> L[4]();
16
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &}
%[[2]][]
->4</
=={{header|Nemerle}}==
<
module Closures
Line 1,394 ⟶ 1,472:
WriteLine($"$(funcs[2]())");
}
}</
{{out}}
<pre>16
4</pre>
=={{header|Nim}}==
<
for i in 0..9:
Line 1,408 ⟶ 1,485:
for i in 0..8:
echo "func[", i, "]: ", funcs[i]()</
=={{header|Objeck}}==
<
class Capture {
Line 1,427 ⟶ 1,503:
}
}
</syntaxhighlight>
{{output}}
Line 1,442 ⟶ 1,518:
81
</pre>
=={{header|Objective-C}}==
{{works with|Cocoa|Mac OS X 10.6+}} with ARC
<
for (int i = 0; i < 10; i++) {
[funcs addObject:[^ { return i * i; } copy]];
Line 1,452 ⟶ 1,527:
int (^foo)(void) = funcs[3];
NSLog(@"%d", foo()); // logs "9"
</syntaxhighlight>
=={{header|OCaml}}==
All functions in OCaml are closures.
<
let cls = Array.init 10 (fun i -> (function () -> i * i)) in
Random.self_init ();
Line 1,464 ⟶ 1,538:
let x = Random.int 9 in
Printf.printf " fun.(%d) = %d\n" x (cls.(x) ());
done</
{{out}}
Line 1,475 ⟶ 1,549:
fun.(6) = 36
</pre>
=={{header|Oforth}}==
<
10 seq map(#newClosure) at(7) perform .</
{{out}}
Line 1,484 ⟶ 1,557:
49
</pre>
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<
{{out}}
<pre>%1 = 25</pre>
=={{header|Perl}}==
<
print $f[$_](), "\n" for (0 .. 8); # call and print all but last</
{{out}}
<pre>
Line 1,507 ⟶ 1,578:
64
</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>
Line 1,558 ⟶ 1,631:
A dictionary based approach may prove somewhat easier:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</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;">tid</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: #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}}==
<
dup *
enddef
Line 1,590 ⟶ 1,665:
var i
i get i swap exec print " " print
endfor</
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<
$funcs = array();
for ($i = 0; $i < 10; $i++) {
Line 1,600 ⟶ 1,674:
}
echo $funcs[3](), "\n"; // prints 9
?></
{{works with|PHP|pre-5.3}}
This method can capture value types like numbers, strings, arrays, etc., but not objects.
<
$funcs = array();
for ($i = 0; $i < 10; $i++) {
Line 1,610 ⟶ 1,684:
}
echo $funcs[3](), "\n"; // prints 9
?></
=={{header|PicoLisp}}==
<
(make
(for @N 10
(link (curry (@N) () (* @N @N))) ) ) )</
Test:
<pre>: ((get FunList 2))
Line 1,623 ⟶ 1,696:
: ((get FunList 8))
-> 64</pre>
=={{header|Pike}}==
<
foreach(enumerate(10);; int i)
{
Line 1,637 ⟶ 1,709:
}(i)
});
}</
=={{header|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()
}
</syntaxhighlight>
<
for ($i = 1; $i -lt 11; $i++)
{
Line 1,657 ⟶ 1,728:
}
}
</syntaxhighlight>
{{Out}}
<pre>
Line 1,673 ⟶ 1,744:
10 100
</pre>
<
$numbers = 1..20 | Get-Random -Count 10
Line 1,685 ⟶ 1,756:
}
}
</syntaxhighlight>
{{Out}}
<pre>
Line 1,701 ⟶ 1,772:
20 400
</pre>
=={{header|Prolog}}==
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
<
Line 1,720 ⟶ 1,790:
call(F, R),
format('Func ~w : ~w~n', [N, R]).
</syntaxhighlight>
{{out}}
<pre> ?- closure.
Line 1,735 ⟶ 1,805:
true.
</pre>
=={{header|Python}}==
The naive way does not work:
<
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 <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.
<
for i in range(10):
funcs.append(lambda i=i: i * i)
print funcs[3]() # prints 9</
or equivalently the list comprehension:
<
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.
<
for i in range(10):
funcs.append((lambda i: lambda: i * i)(i))
print funcs[3]() # prints 9</
or equivalently the list comprehension:
<
print funcs[3]() # prints 9</
In this case it is also possible to use <code>map()</code> since the function passed to it creates a new scope
<
print funcs[3]() # prints 9</
It is also possible to use <code>eval</code>.
<
print funcs[3]() # prints 9</
=={{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.
<
10 times
Line 1,779 ⟶ 1,847:
' functions put ]
5 functions do echo</
{{out}}
<pre>25</pre>
=={{header|R}}==
Line 1,792 ⟶ 1,859:
what you expect.
<syntaxhighlight lang="R">
# assign 's' a list of ten functions
s <- sapply (1:10, # integers 1..10 become argument 'x' below
Line 1,802 ⟶ 1,869:
s[[5]]() # call the fifth function in the list of returned functions
[1] 25 # returns vector of length 1 with the value 25
</syntaxhighlight>
Note that I bound the captured variable as the default argument on a unary function.
Line 1,808 ⟶ 1,875:
ignores the default argument.
<syntaxhighlight lang="R">
s[[5]](10)
[1] 100
</syntaxhighlight>
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.
<syntaxhighlight lang="R">
s <- sapply (1:10,
function (x) {
Line 1,835 ⟶ 1,902:
s[[1]]()
[1] 4 # now 2^2
</syntaxhighlight>
As shown, each instance increments separately.
Line 1,844 ⟶ 1,911:
I think that modifying the bound variable can be done in a simpler way.
Instead of:
<
substitute:
<
Testing:
<pre>
Line 1,862 ⟶ 1,929:
[1] 16
</pre>
=={{header|Racket}}==
<
#lang racket
(define functions (for/list ([i 10]) (λ() (* i i))))
(map (λ(f) (f)) functions)
</syntaxhighlight>
{{out}}
<
'(0 1 4 9 16 25 36 49 64 81)
</syntaxhighlight>
=={{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"
take { $i * $i }
}
.().say for @c.pick(*); # call them in random order</
{{out}}
<pre>36
Line 1,895 ⟶ 1,960:
49</pre>
Or equivalently, using a more functional notation:
<syntaxhighlight lang="raku"
=={{header|Red}}==
<
funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]]
>> funs/7
== 49
</syntaxhighlight>
=={{header|REXX}}==
This REXX version supports both a one─ and zero─based list (it can be specified at the command line.)
Line 1,913 ⟶ 1,976:
No error checking is performed on the user input(s).
<
parse arg seed base $ /*obtain optional arguments from the CL*/
if datatype(seed, 'W') then call random ,,seed /*Not given? Use random start seed. */
Line 1,937 ⟶ 2,000:
.9: return .(9) /* ' .9 " " " " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.: arg #; _=wordpos(#,$); if _==0 then return 'not in the list.'; return (_-(\base))**2</
{{out|output|text= when using the default input which assume a zero─based list):}}
<pre>
Line 1,948 ⟶ 2,011:
function .0 returned 100
</pre>
=={{header|Ring}}==
<
x = funcs(7)
see x + nl
Line 1,960 ⟶ 2,022:
next
return fn
</syntaxhighlight>
Output:
<pre>
Line 1,971 ⟶ 2,033:
49
</pre>
=={{header|Ruby}}==
<
p procs[7].call # => 49</
In Ruby, lambdas (and procs) are closures.
=={{header|Rust}}==
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.
<
let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect();
println!("7th val: {}", fs[7]());
}</
{{out}}
<pre>7th val: 49</pre>
=={{header|Scala}}==
<
0 to 8 foreach (i=> println(closures(i)()))
println("---\n"+closures(7)())</
{{out}}
<pre>0
Line 2,006 ⟶ 2,065:
---
49</pre>
=={{header|Scheme}}==
<
(define (build-list-of-functions n i list)
(if (< i n)
Line 2,019 ⟶ 2,077:
(map (lambda (f) (f)) list-of-functions)
((list-ref list-of-functions 8))</
{{out}}
<
81</
----
Using Scheme [http://srfi.schemers.org/srfi-1/srfi-1.html SRFI 1] ''iota'' procedure can be simplified to:
<
(define list-of-functions (map (lambda (x) (lambda () (* x x))) (iota 0 1 10)))
Line 2,035 ⟶ 2,093:
(map (lambda (n) (n)) list-of-functions)
(newline)
</syntaxhighlight>
=={{header|Sidef}}==
<
10.of {|i| func(j){i * j} }
)
Line 2,044 ⟶ 2,101:
9.times { |j|
say f[j](j)
}</
{{out}}
<pre>
Line 2,059 ⟶ 2,116:
Starting from i=1:
<
func(j){i * j}
}
Line 2,065 ⟶ 2,122:
for j (1..9) {
say f[j-1](j)
}</
{{out}}
<pre>
Line 2,078 ⟶ 2,135:
81
</pre>
=={{header|Smalltalk}}==
<
(funcs at: 3) value displayNl .</
{{out}}
<pre>9</pre>
=={{header|Sparkling}}==
In Sparkling, upvalues (variables in the closure) are captured by value.
<
for var i = 0; i < 10; i++ {
fnlist[i] = function() {
Line 2,096 ⟶ 2,151:
print(fnlist[3]()); // prints 9
print(fnlist[5]()); // prints 25</
Alternately:
<
return function() {
return v * v;
Line 2,107 ⟶ 2,162:
print(fnlist[3]()); // prints 9
print(fnlist[5]()); // prints 25</
=={{header|Standard ML}}==
<
List.map (fn x => x () ) ( List.tabulate (10,(fn i => (fn ()=> i*i)) ) ) ;
</
<
val it = [0,1,4,9,16,25,36,49,64,81] : int list
</syntaxhighlight>
=={{header|Swift}}==
By default, Swift captures variables by reference. A naive implementation like the following C-style for loop does not work:
<
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:
<
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:
<
for var i = 0; i < 10; i++ {
funcs.append({ [i] in i * i })
}
println(funcs[3]()) // prints 9</
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:
<
println(funcs[3]()) // prints 9</
=={{header|Tcl}}==
Tcl does not support closures (either value-capturing or variable-capturing) by default, but value-capturing closures are easy to emulate.
<
# Builds a value-capturing closure; does NOT couple variables
proc closure {script} {
Line 2,180 ⟶ 2,232:
set idx [expr {int(rand()*9)}]; # pick random int from [0..9)
puts $idx=>[{*}[lindex $theClosures $idx]]
}</
{{out}}
<pre>
Line 2,189 ⟶ 2,241:
8=>64
</pre>
=={{header|TXR}}==
====Sugared====
<
[mapcar call [funs 0..-1]])</
{{out}}
<
====Desugared====
Line 2,207 ⟶ 2,258:
The explicit <code>lambda</code> structure here is much like the implicit ones in the "Sugared" example:
<
;; (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====
Line 2,249 ⟶ 2,300:
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}}==
<
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())")</
{{out}}
Line 2,272 ⟶ 2,322:
=={{header|Yabasic}}==
<
dim funcs$(10)
Line 2,286 ⟶ 2,336:
print execute(funcs$(i), i)
next
</syntaxhighlight>
=={{header|zkl}}==
Create a closure of the index over a square function
<
list:=(0).pump(10,List,fcn(i){i*i}.fp);
foreach n in (list.len()-1) { list[n]().println() }
list.run(True).println()</
{{out}}
<pre>
Line 2,307 ⟶ 2,356:
L(0,1,4,9,16,25,36,49,64,81)
</pre>
{{omit from|BASIC}}
{{omit from|Brlcad}}
Line 2,314 ⟶ 2,362:
{{omit from|PureBasic}}
{{omit from|ZX Spectrum Basic}}
|