Search code examples
delphicollectionsdelphi-xe2spring4d

Is there a map function?


I just wrote this function:

class function TGenerics.Map<TFrom, TTo>(const AEnumerable: IEnumerable<TFrom>;
  const AConverter: TConstFunc<TFrom, TTo>): IList<TTo>;
var
  L: IList<TTo>;
begin
  L := TCollections.CreateList<TTo>;
  AEnumerable.ForEach(
    procedure(const AItem: TFrom)
    begin
      L.Add(AConverter(AItem));
    end
  );
  Result := L;
end;

This is roughly equivalent to Haskells map (or fmap, liftM, etc).

So I'm wondering does something like this already exist in Spring4D?


Solution

  • What you are looking for is called TEnumerable.Select<T, TResult> in Spring.Collections (introduced for the not yet released 1.2 - see develop branch).

    The reason for IEnumerable<T> not having a Select method is that interface types cannot have parameterized methods.

    Keep in mind that the implementation in Spring4D is different from yours because it uses streaming and deferred execution.