6

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?

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
  • 1
    It's really odd that it supports `Where` (Haskell `filter`) but not `Select` (Haskell `map`) – Benjamin Gruenbaum May 05 '15 at 09:58
  • 2
    Just a side note - OmniThreadLibrary has a parallel version of a similar contruct which maps TArray to TArray (http://www.thedelphigeek.com/2015/01/parallel-map.html). – gabr May 05 '15 at 09:58

1 Answers1

10

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.

Stefan Glienke
  • 20,860
  • 2
  • 48
  • 102
  • 1
    I know it's not a perfect (or even correct) solution and all, but I've extended IList with a non-parameterised Select function, which allow you to map to the type of the list. It's often come in handy – Mads Boyd-Madsen May 18 '18 at 16:18