【问题标题】:map-indexed alternative for reducersreducer 的 map-indexed 替代方案
【发布时间】:2017-04-03 20:03:58
【问题描述】:

clojure.core.reducers 是否有 map-indexed 替代方案?我想要像r/map 那样懒惰地工作的东西(不构造新序列)。

【问题讨论】:

  • 如果你不只绑定reducers,你可以使用map-indexed的转换器版本,这样可以避免创建中间集合

标签: clojure


【解决方案1】:

我怀疑你真正想要使用的是 transducer,因为 map-indexed 有一个 1-arity 版本(map、filter 和许多其他核心函数也是如此),它返回一个转换器。传感器是可组合的,不会创建中间序列。这是一个简短的例子:

(def xf (comp
          (map-indexed (fn [i value] [i value]))
          (filter (fn [[i value]] (odd? i)))
          (map second)))

这就是说:使用map-indexed生成一个带索引的向量,只过滤掉索引为奇数的向量,得到第二个元素。 (filter odd? collection) 是一种冗长的说法,但仅用于示例目的。

您可以将其与into 一起使用:

(into [] xf "ThisIsATest")
=> [\h \s \s \T \s]

或者您可以使用transduce 函数并将str 应用于结果:

(transduce xf str "ThisIsATest")
=> "hssTs"

【讨论】:

  • 漂亮、干净、简单。也应标记为“Transducer De-Mystifier”示例。
  • 这实际上根本不是(filter odd? coll),因为您过滤的是索引,而不是值。相反,它是(take-nth 2 (rest coll))。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 2015-07-18
  • 1970-01-01
相关资源
最近更新 更多