store/[org.clojure/clojure "1.6.0"] clj::clojure.core/assoc

Community Documentation

Edit

Usage

[map key val]
[map key val & kvs]

Docs

From asso[ciate]. 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.

Notes

A thin wrapper around clojure.lang.Associative.

When used on a vector, the index cannot exceed the length of the vector. That is, associate is an update operation on vectors, it cannot be used to extend a vector to arbitrary length. To extend a vector, use clj::clojure.core/conj instead.

Source

(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
        (if (next kvs)
          (recur ret (first kvs) (second kvs) (nnext kvs))
          (throw (IllegalArgumentException.
                  "assoc expects even number of arguments after map/vector, found odd number")))
        ret)))))

Example 1

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

(assoc {:key1 "old value1" :key2 "value2"} :key1 "value1" :key3 "value3")
;; => {:key3 "value3", :key2 "value2", :key1 "value1"}

(assoc nil :key1 4)
;; => {:key1 4}

(assoc [1 2 3] 0 10)
;; => [10 2 3]

(assoc [1 2 3] 3 10)
;; => [1 2 3 10]

(assoc [1 2 3] 4 10)
;; => java.lang.IndexOutOfBoundsException (NO_SOURCE_FILE:0)

;; From http://clojure-examples.appspot.com/clojure.core/assoc

Example 2

Edit
(def test-map {:account-no 12345678 :lname "Jones" :fnam "Fred"})
(assoc test-map :fnam "Sue")
{:account-no 12345678, :lname "Jones", :fnam "Sue"}

Uses on crossclj