[英]Clojure defrecord - how to update multiple vectors within
I have a datatype defined with defrecord, which contains two vectors: 我有一个用defrecord定义的数据类型,其中包含两个向量:
(defrecord MyType [a b])
(def mytype (->MyType [1 2 3] [4 5 6]))
I want to have a function update both vectors and return a new MyType. 我想让一个函数同时更新两个向量并返回一个新的MyType。 The only way I can think of to do that is via nested assoc calls: 我能想到的唯一方法是通过嵌套的assoc调用:
(defn mutate-mytype [mytype x y]
(assoc mytype :a (assoc (:a mytype) x y)
:b (assoc (:b mytype) x y)))
Example output: 输出示例:
user=> (mutate-mytype mytype 1 7)
#user.MyType{:a [1 7 3], :b [4 7 6]}
Question: Is there a better way to write that mutate-mytype method? 问题:是否有更好的方法来编写mutate-mytype方法?
Your implementation is perfectly fine. 您的实现是完美的。
There are a few alternatives, eg you might consider using assoc-in
and the ->
threading operator: 有几种选择,例如,您可以考虑使用assoc-in
和->
线程运算符:
(defn mutate-mytype [mytype x y]
(-> mytype
(assoc-in [:a x] y)
(assoc-in [:b x] y)))
This doesn't really have any advantages over your approach in this case, but it might make the code more readable if you had more deep nesting going on. 在这种情况下,这实际上没有比您的方法有任何优势,但是如果您进行了更多的深层嵌套,则可能会使代码更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.