RosettaCodeData/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi

28 lines
564 B
Text
Raw Permalink Normal View History

2015-02-20 09:02:09 -05:00
program Project1;
type
2015-11-18 06:14:39 +00:00
TFuncIntResult = reference to function: Integer;
2015-02-20 09:02:09 -05:00
2015-11-18 06:14:39 +00:00
// 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;
2015-02-20 09:02:09 -05:00
2015-11-18 06:14:39 +00:00
var
Funcs: array[0..9] of TFuncIntResult;
i: integer;
2015-02-20 09:02:09 -05:00
begin
2015-11-18 06:14:39 +00:00
// create 10 anonymous functions
2015-02-20 09:02:09 -05:00
for i := Low(Funcs) to High(Funcs) do
2015-11-18 06:14:39 +00:00
Funcs[i] := CreateFunc(i);
2015-02-20 09:02:09 -05:00
// call all 10 functions
for i := Low(Funcs) to High(Funcs) do
2015-11-18 06:14:39 +00:00
Writeln(Funcs[i]());
2015-02-20 09:02:09 -05:00
end.