You're viewing version 1.2.0 of update-in. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

update-in

clojure.core

  • (update-in m [k & ks] f & args)
'Updates' a value in a nested associative structure, where ks is a
sequence of keys and f is a function that will take the old value
and any supplied args and return the new value, and returns a new
nested structure. If any levels do not exist, hash-maps will be
created.

4 Examples top

  • user=> (def users [{:name "James" :age 26}  {:name "John" :age 43}])
    #'user/users
    
    user=> (update-in users [1 :age] inc)
    
    [{:name "James", :age 26} {:name "John", :age 44}]
    
  • user=> (def p {:name "James" :age 26})
    #'user/p
    
    user=> (update-in p [:age] inc)
    {:name "James", :age 27}
    
    ;; remember, the value of p hasn't changed!
    user=> (update-in p [:age] + 10)
    {:name "James", :age 36}
    
    
  • (defn char-cnt [s]
      "Counts occurence of each character in s"
      (reduce
        (fn [m k]
          (update-in m [k] (fnil inc 0)))
      {}
      (seq s)))
    ;Note use of fnil above - returns 0 if nil is passed to inc (avoids null pointer exception)
    
  • ; f has args 
    user=> (update-in {:a 3} [:a] / 4 5)
    {:a 3/20}
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:4949 top

(defn update-in
  "'Updates' a value in a nested associative structure, where ks is a
  sequence of keys and f is a function that will take the old value
  and any supplied args and return the new value, and returns a new
  nested structure.  If any levels do not exist, hash-maps will be
  created."
  {:added "1.0"}
  ([m [k & ks] f & args]
   (if ks
     (assoc m k (apply update-in (get m k) ks f args))
     (assoc m k (apply f (get m k) args)))))
Vars in clojure.core/update-in: apply assoc defn get

Comments top

No comments for update-in. Log in to add a comment.