我有一个用defrecord定义的数据类型,它包含两个向量:
(defrecord MyType [a b])
(def mytype (->MyType [1 2 3] [4 5 6]))
我想让一个函数更新两个向量并返回一个新的MyType。我能想到的唯一方法是通过嵌套的assoc调用:
(defn mutate-mytype [mytype x y]
(assoc mytype :a (assoc (:a mytype) x y)
:b (assoc (:b mytype) x y)))
示例输出:
user=> (mutate-mytype mytype 1 7)
#user.MyType{:a [1 7 3], :b [4 7 6]}
问题:有没有更好的方法来编写mutate-mytype方法?
答案 0 :(得分:6)
您的实施完全没问题。
有一些替代方案,例如您可以考虑使用assoc-in
和->
线程运算符:
(defn mutate-mytype [mytype x y]
(-> mytype
(assoc-in [:a x] y)
(assoc-in [:b x] y)))
在这种情况下,这与您的方法没有任何优势,但如果您进行更深层次的嵌套,它可能会使代码更具可读性。