{$ifdef FPC}
{$ifdef VER3_2} {$message warn 'This code needs FPC >= 3.3.x'} begin end. {$endif}
{$mode objfpc}{$H+}{$J-}
{$modeswitch functionreferences}
{$modeswitch anonymousfunctions}
{$endif}
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
uses SysUtils, Generics.Collections;
type
TIntMapFunc =
reference to function(const Index, Item: Integer): Integer;
TIntMapProc =
reference to procedure(const Index, Item: Integer);
TMyInts = class({$ifdef FPC}specialize{$endif} TList<Integer>)
procedure Map(const AFunc: TIntMapFunc);
procedure ForEach(const AProc: TIntMapProc);
end;
procedure TMyInts.Map(const AFunc: TIntMapFunc);
var
Index: Integer;
begin
for Index := 0 to Count - 1 do
Items[Index] := AFunc(Index, Items[Index]);
end;
procedure TMyInts.ForEach(const AProc: TIntMapProc);
var
Index: Integer;
begin
for Index := 0 to Count - 1 do
AProc(Index, Items[Index]);
end;
var
MyList: TMyInts;
I: Integer;
F: TIntMapFunc;
begin
MyList := TMyInts.Create;
try
for I := 0 to 10 do
MyList.Add(I);
F := function(const Index, Item: Integer): Integer
begin
Result := Item + 1;
end;
MyList.Map(F);
MyList.Map(F);
MyList.Map(F);
MyList.Map(function(const Index, Item: Integer): Integer
begin
Result := Item * Item;
end);
MyList.ForEach(procedure(const Index, Item: Integer)
begin
WriteLn('Index: ', Index, ', Item: ', Item);
WriteLn(' If we would process it by F: ', F(Index, Item));
end);
finally FreeAndNil(MyList) end;
end.