【问题标题】:Is there a map function?有地图功能吗?
【发布时间】:2015-05-05 09:54:43
【问题描述】:

我刚刚写了这个函数:

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;

这大致相当于 Haskells map(或 fmapliftM 等)。

所以我想知道这样的东西在 Spring4D 中是否已经存在?

【问题讨论】:

  • 它支持Where (Haskell filter) 但不支持Select (Haskell map) 真的很奇怪
  • 附带说明 - OmniThreadLibrary 有一个类似结构的并行版本,它将 TArray 映射到 TArray (thedelphigeek.com/2015/01/parallel-map.html)。

标签: delphi collections delphi-xe2 spring4d


【解决方案1】:

您要查找的内容在 Spring.Collections 中称为 TEnumerable.Select&lt;T, TResult&gt;(为尚未发布的 1.2 引入 - 请参阅开发分支)。

IEnumerable&lt;T&gt; 没有 Select 方法的原因是接口类型为cannot have parameterized methods

请记住,Spring4D 中的实现与您的不同,因为它使用流式执行和延迟执行。

【讨论】:

  • 我知道这不是一个完美(甚至是正确)的解决方案,但我已经用非参数化的 Select 函数扩展了 IList,它允许您映射到列表的类型。它经常派上用场
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 2013-12-31
  • 2012-06-13
  • 2020-03-02
  • 2019-01-31
相关资源
最近更新 更多