assoc

added
1.0

ns
clojure.core

type
function

(assoc map key val) (assoc map key val & kvs)

assoc[iate]. When applied to a map, returns a new map of the
same (hashed/sorted) type, that contains the mapping of key(s) to
val(s). When applied to a vector, returns a new vector that
contains val at index. Note - index must be <= (count vector).

                (assoc {} :key1 "value" :key2 "another value")
;;=> {:key2 "another value", :key1 "value"}

;; Here we see an overwrite by a second entry with the same key
(assoc {:key1 "old value1" :key2 "value2"} 
        :key1 "value1" :key3 "value3")
;;=> {:key3 "value3", :key2 "value2", :key1 "value1"}

;; We see a nil being treated as an empty map
(assoc nil :key1 4)
;;=> {:key1 4}

;; 'assoc' can be used on a vector (but not a list), in this way: 
(assoc vec index replacement)

(assoc [1 2 3] 0 10)     ;;=> [10 2 3]
(assoc [1 2 3] 3 10)     ;;=> [1 2 3 10]
(assoc [1 2 3] 2 '(4 6)) ;;=> [1 2 (4 6)]
;; but if the index does not exist, it is not added automagically
(assoc [1 2 3] 4 10)
;; java.lang.IndexOutOfBoundsException (NO_SOURCE_FILE:0)

;; From http://clojure-examples.appspot.com/clojure.core/assoc
            
                ;; here is an example of updating a field in a map.
(def test-map {:account-no 12345678 :lname "Jones" :fnam "Fred"})
(assoc test-map :fnam "Sue")
;;=> {:account-no 12345678, :lname "Jones", :fnam "Sue"}

;; notice that test-map is unchanged
test-map
;;=> {:account-no 12345678 :lname "Jones" :fnam "Fred"})
            
                ;; beware of this
(assoc {} nil nil)
;;=> {nil nil}