简体   繁体   中英

Why does (assoc-in everything …) not change everything?

(def everything (vec (repeat 5 (vec (repeat 5 [0 0 0])))))

(assoc-in everything [3 3] [255 255 255])

(get-in everything [3 3])

This returns [0 0 0], not [255 255 255]. Why?

Clojure data structures are immutable, so assoc-in does not change the vector, but returns a new vector with the changes. To have any affect, the results of assoc-in have to be captured in a binding, passed to a function, etc.

(get-in (assoc-in everything [3 3] [255 255 255]) [3 3])
;=> [255 255 255]

Note, due to structural sharing, the new vector is not a complete copy of the old with just one change, but a much smaller new tree, reusing much of the old vector.

Vectors are immutable. assoc-in when applied to an immutable data structure just returns a new data structure, and doesn't touch the original. You'll be wanting to give the return value a new name with, eg, (def foo (assoc-in everything [3 3] [255 255 255])) , or else pass it to some other function or something.

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