I have a datatype defined with defrecord, which contains two vectors:
(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. The only way I can think of to do that is via nested assoc calls:
(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?
Your implementation is perfectly fine.
There are a few alternatives, e.g. you might consider using
assoc-inand the->threading operator: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.