update

added
1.7

ns
clojure.core

type
function

(update m k f) (update m k f x) (update m k f x y) (update m k f x y z) (update m k f x y z & more)

'Updates' a value in an associative structure, where k is a
key and f is a function that will take the old value
and any supplied args and return the new value, and returns a new
structure.  If the key does not exist, nil is passed as the old value.

                (def p {:name "James" :age 26})
#'user/p

(update p :age inc)
;;=> {:name "James", :age 27}

;; remember, the value of p hasn't changed!
(update p :age + 10)
;;=> {:name "James", :age 36}

;; Here we see that the keyed object is 
;; the first argument in the function call.
;; i.e. :age (- 26 10) => 16
(update p :age - 10)
;;=> {:name "James", :age 16}
            
                ;; the map in update can be nil, and f will still be applied to nil and 
;; return a value

(def empty-map nil)
#'user/empty-map

(update empty-map :some-key #(str "foo" %))
;;=> {:some-key "foo"}

            
                ;; can also use in []

user=> (update [1 2 3] 0 inc)
;;=> [2 2 3]

user=> (update [] 0 #(str "foo" %))
;;=> ["foo"]