如何处理向量中的每个项目并引用Clojure中的先前值? [英] How do I operate on every item in a vector AND refer to a previous value in Clojure?
本文介绍了如何处理向量中的每个项目并引用Clojure中的先前值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出:
(def my-vec [{:a "foo" :b 10} {:a "bar" :b 13} {:a "baz" :b 7}])
如何迭代每个元素要打印该元素的:a和所有:b的总和到那个点?即:
How could iterate over each element to print that element's :a and the sum of all :b's to that point? That is:
foo 10
bar 23
baz 30
"foo" 10
"bar" 23
"baz" 30
我正在尝试类似的事情,但无济于事:
I'm trying things like this to no avail:
; Does not work!
(map #(prn (:a %2) %1) (iterate #(+ (:b %2) %1) 0)) my-vec)
这是行不通的,因为 iterate lazy-seq不能引用my-vec中的当前元素(据我所知)。
This doesn't work because the "iterate" lazy-seq can't refer to the current element in my-vec (as far as I can tell).
TIA!肖恩(Sean)
TIA! Sean
推荐答案
user> (reduce (fn [total {:keys [a b]}]
(let [total (+ total b)]
(prn a total)
total))
0 my-vec)
"foo" 10
"bar" 23
"baz" 30
30
这篇关于如何处理向量中的每个项目并引用Clojure中的先前值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文