LoginSignup
1
0

More than 5 years have passed since last update.

merge で値も型も右側のhashmapを優先したい

Last updated at Posted at 2012-03-16

merge は2つのhashmapを合併したhashmapを作る。
同じkeyがあると右側のhashmapの値が優先される。
optionをhashmapで取るようにしてデフォルト値と合わせるときに便利。
値は右側が優先されるが、型は左側が保存される。
これはdefrecordで作った型をmergeしたい時に問題になる。

(defrecord Person [a b])
(def person (Person. 1 1))
;=> #cljs.user.Person{:a 1, :b 1}

用意したhashmapとmergeしたいが、値も型もpersonの方を優先したい。

(merge person {:a 2 :c 2})
;=> #cljs.user.Person{:a 2, :b 1, :c 2} ;; 値は右側が優先され型はPersonのまま。
(merge {:a 2 :c 2} person)
;=> {:a 1, :c 2, :b 1}  ;; 値はpersonが優先されるが、型がPersonじゃなくなる。

workaround的な対処だがpersonで挟む。

(merge person {:a 2 :c 2} person)
;=> #cljs.user.Person{:a 1, :b 1, :c 2}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0