Closures/Value capture: Difference between revisions

Content added Content deleted
Line 898: Line 898:
81
81
</pre>
</pre>
=={{header|FreePascal}}==
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>

=={{header|Go}}==
=={{header|Go}}==
<syntaxhighlight lang="go">package main
<syntaxhighlight lang="go">package main