gpt4 book ai didi

clojure - Clojure 中带有累加器的映射?

转载 作者:行者123 更新时间:2023-12-02 13:42:31 24 4
gpt4 key购买 nike

我想按顺序映射一个序列,但想向前传送累加器值,就像在reduce中一样。

示例用例:获取一个向量并返回一个运行总计,每个值乘以 2。

(defn map-with-accumulator
"Map over input but with an accumulator. func accepts [value accumulator] and returns [new-value new-accumulator]."
[func accumulator collection]
(if (empty? collection)
nil
(let [[this-value new-accumulator] (func (first collection) accumulator)]
(cons this-value (map-with-accumulator func new-accumulator (rest collection))))))

(defn double-running-sum
[value accumulator]
[(* 2 (+ value accumulator)) (+ value accumulator)])

这给出

(prn (pr-str (map-with-accumulator double-running-sum 0 [1 2 3 4 5])))

>>> (2 6 12 20 30)

另一个例子来说明一般性,将运行总和打印为星号和原始数字。一个稍微复杂的示例,但演示了我需要将正在运行的累加器保留在 map 函数中:

(defn stars [n] (apply str (take n (repeat \*))))

(defn stars-sum [value accumulator]
[[(stars (+ value accumulator)) value] (+ value accumulator)])

(prn (pr-str (map-with-accumulator stars-sum 0 [1 2 3 4 5])))
>>> (["*" 1] ["***" 2] ["******" 3] ["**********" 4] ["***************" 5])

这工作得很好,但我希望这是一种常见的模式,并且某种map-with-accumulator存在于core中。是吗?

最佳答案

您应该考虑减少。对于这个具体案例:

(reductions #(+ % (* 2 %2)) 2 (range 2 6))

产生

(2 6 12 20 30)

关于clojure - Clojure 中带有累加器的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23849231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com