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).
user=> (assoc {} :key1 "value" :key2 "another value")
{:key2 "another value", :key1 "value"}
user=> (assoc {:key1 "old value1" :key2 "value2"} :key1 "value1" :key3 "value3")
{:key3 "value3", :key2 "value2", :key1 "value1"}
user=> (assoc [1 2 3] 0 10)
[10 2 3]
user=> (assoc [1 2 3] 3 10)
[1 2 3 10]
user=> (assoc [1 2 3] 4 10)
java.lang.IndexOutOfBoundsException (NO_SOURCE_FILE:0)
;; From http://clojure-examples.appspot.com/clojure.core/assoc
(def test-map {:account-no 12345678 :lname "Jones" :fnam "Fred"})
(assoc test-map :fnam "Sue")
{:account-no 12345678, :lname "Jones", :fnam "Sue"}
(def
^{:arglists '([map key val] [map key val & kvs])
:doc "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)."
:added "1.0"
:static true}
assoc
(fn ^:static assoc
([map key val] (. clojure.lang.RT (assoc map key val)))
([map key val & kvs]
(let [ret (assoc map key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret)))))
Comments top
1 comment(s) for assoc.
Here is a version that will create a vector when the key is numerical. This may be useful instead of throwing an IndexOutOfBoundsException.
(defn assoc-in-idx [m [k & ks] v] (let [value (get m k (when (number? (first ks)) [])) m (if (and (vector? m) (number? k) (-> m count (< k))) (reduce (fn [m _] (conj m nil)) m (range (count m) k)) m) v (if ks (assoc-in-idx value ks v) v)] (assoc m k v)))(defn assoc-in-idx [m [k & ks] v] (let [value (get m k (when (number? (first ks)) [])) m (if (and (vector? m) (number? k) (-> m count (< k))) (reduce (fn [m _] (conj m nil)) m (range (count m) k)) m) v (if ks (assoc-in-idx value ks v) v)] (assoc m k v)))