简体   繁体   中英

Clojure defrecord - how to update multiple vectors within

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, eg you might consider using assoc-in and the -> threading operator:

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM