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?
In mathematics, a map is often used as a synonym for a function, but may also refer to some generalizations. Originally, this was an abbreviation of mapping, which often refers to the action of applying a function to the elements of its domain.
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.
Definition and Usage. map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With