3

我想知道 Clojure 中是否有与此等效的函数:

(defn reduce-1 [f val coll]
  (loop [[head & tail] coll
           out val]
      (if head
        (recur tail (f out head tail))
        out)))

请注意,这与通常的 'reduce 不同,因为 'tail 被传递给 'f。

我正在使用这个概念(递归地收集列表中第一个和其余列表的交互),以至于我开始怀疑是否有一个标准函数。

4

1 回答 1

2

你可以使用iterate.

(defn reduce-with-tail
  [f initial coll]
  (->> (seq coll)
    (iterate next)
    (take-while identity)
    (reduce (fn [initial [head & tail]] (f initial head tail)) initial)))
于 2012-05-30T11:31:48.030 回答