9. 12. 2016
Generic Reduce for Delphi
Simple Reduce() implementation for Delphi 2009+:
unit MapReduce;
interface
uses
System.SysUtils, System.Generics.Collections;
type
TMapReduce = record
public
class function Reduce<T, U>
const AList: TEnumerable<U>; AAcc: T): T; static;
end;
implementation
class function TMapReduce.Reduce<T, U>
const AList: TEnumerable<U>; AAcc: T): T;
var
Item: U;
begin
for Item in AList do
AAcc := AFunc(Item, AAcc);
Result := AAcc;
end;
end.
Usage:
var
List: TList<TButton>
ButtonCaptions: string;
begin
List := TList<TButton>
try
List.Add(Button1);
List.Add(Button2);
List.Add(Button3);
ButtonCaptions := TMapReduce.Reduce<string, TButton>(
function(AButton: TButton; S: string): string
begin
Result := AButton.Caption;
if S <> '' then
Result := S + ',' + Result;
end, List, '');
finally
List.Free;
end;
end;
Štítky: Delphi