如果您总是要立即更新记录
(def records (atom [(->Record "John" 12 123 nil)
(->Record "Joe" 13 3 nil)
(->Record "Jon" 14 4 nil)]))
(reset! records (map #(assoc % :Class_Index (+ (:Age %) (:Index %)))
@records))
(pprint records)
-> #<Atom@131bf42:
({:Name "John", :Age 12, :Index 123, :Class_Index 135}
{:Name "Joe", :Age 13, :Index 3, :Class_Index 16}
{:Name "Jon", :Age 14, :Index 4, :Class_Index 18})>
否则
(def records [(ref (->Record "John" 12 123 nil))
(ref (->Record "Joe" 13 3 nil))
(ref (->Record "Jon" 14 4 nil))])
(dosync (doseq [record records]
(alter record #(assoc % :Class_Index (+ (:Age %) (:Index %))))))
(pprint records)
-> [#<Ref@178f7a8: {:Name "John", :Age 12, :Index 123, :Class_Index 135}>
#<Ref@129617b: {:Name "Joe", :Age 13, :Index 3, :Class_Index 16}>
#<Ref@ac9126: {:Name "Jon", :Age 14, :Index 4, :Class_Index 18}>]
更新。如果集合中有很多元素,那么最好使用 clojure 映射而不是记录对象。只需用地图替换记录定义
(def records (atom [{:Name "John", :Age 12, :Index 123, :Class_Index nil}
{:Name "Joe", :Age 13, :Index 3, :Class_Index nil}
{:Name "Jon", :Age 14, :Index 4, :Class_Index nil}]))
或者是否有物品来源
(def records (atom (source-fn ...)))
在这种情况下,没有内存开销。其余代码将是相同的。