我有一张地图清单:

(def mylist
  [{:id 1 :sub [{:subid 1} {:subid 2}]}
   {:id 2 :sub [{:subid 3}]}])


我想向包含:sub中项目计数的列表的每个地图元素添加一个新的键/值对:

[{:id 1 :sub [{:subid 1} {:subid 2}] :subcount 2}
 {:id 2 :sub [{:subid 3}] :subcount 1}]


我怎样才能做到这一点?

最佳答案

在Clojure中,“添加到地图”是使用assoc完成的,它会返回添加了指定值的新地图,通常,如果要对事物集合执行相同的操作,请使用map功能。

(defn subcount
  "return the number of items in the :sub of m"
  [m]
  (count (:sub m)))

(defn add-count
  "add subcount to the given map"
  [m]
  (assoc m :subcount (subcount m)))

(defn add-counts
  "add subcount to all the objects"
  [objects]
  (map add-count objects))

(def mylist
  [{:id 1 :sub [{:subid 1} {:subid 2}]}
   {:id 2 :sub [{:subid 3}]}])

(add-counts mylist)
=> ({:sub [{:subid 1} {:subid 2}], :subcount 2, :id 1} {:sub [{:subid 3}], :subcount 1, :id 2})

10-02 18:14