Skip to content

clojure.core/assoc

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 9 Runnable: 8
([map key val] [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).

Examples

by zk on . May have evaluation errors.
by octopusgrabbus on
by nickzam on
by ibercode on
by ibercode on
by eddy147 on
by victorb on
by adanhawth on
by kimim on

Note by l0st3d

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)))

Note by simlegate

the API is blurry When applied to a vector

;; should indicate following
(assoc vector index val) 

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.