Clojure-计算地图向量的累积和

时间:2019-07-30 18:24:24

标签: clojure

我想计算地图矢量中一个字段的累积和。发件人:

(def data
  [{:id 1 :name "John1" :income 5000}
   {:id 2 :name "John2" :income 6000}
   {:id 3 :name "John3" :income 7000}])

收件人:

(def data
  [{:id 1 :name "John1" :income 5000}
   {:id 2 :name "John2" :income 11000}
   {:id 3 :name "John3" :income 18000}])

我有类似(reductions + (map :income data))的东西来进行计算,但是如何形成新矢量?

3 个答案:

答案 0 :(得分:3)

要继续您的解决方案(并且如果您不介意重复数据两次):

(map #(assoc %1 :income %2) data (reductions + (map :income data)))
; => ({:id 1, :income 5000, :name "John1"}
; =>  {:id 2, :income 11000, :name "John2"}
; =>  {:id 3, :income 18000, :name "John3"})

(或使用mapv保持向量)

答案 1 :(得分:2)

> (reduce #(conj %1 (assoc %2 :income (+ (:income (last %1)) (:income %2)))) (vector (first data)) (rest data))
[{:id 1, :name "John1", :income 5000}
 {:id 2, :name "John2", :income 11000}
 {:id 3, :name "John3", :income 18000}]

答案 2 :(得分:1)

使用幽灵:

(transform (subselect ALL :income) #(reductions + %) data)

相关问题