assoc

clojure.core

  • (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).

2 Examples top

  • 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 nil :key1 4)
    {:key1 4}
    
    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"}
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:177 top

(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)))))
Vars in clojure.core/assoc:
Used in 0 other vars

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)))
Log in to add a comment.