assoc and update

Working with assoc and update in Clojure.

Code entered at 2017-10-04_19.34.11.

(def hello "hello")

(assoc (hash-map :ga '1 :il '3) :ak '4)
;; => {:ga 1, :il 3, :ak 4}

(assoc ['a 'b 'c 'd] 0 'e)
;; => [e b c d]
(assoc ['a 'b 'c 'd] 2 'e)
;; => [a b e d]
(def my-vec [1 2 3 4])
my-vec
;; => [1 2 3 4]
(assoc my-vec 0 "Hello")
;; => ["Hello" 2 3 4]
(assoc my-vec 1 "Hello")
;; => [1 "Hello" 3 4]
(assoc my-vec 3 "Hello")
;; => [1 2 3 "Hello"]
;; what if we go with an index past the size?
(assoc my-vec 4 "Hello")
;; => [1 2 3 4 "Hello"]
;; what about two past?
(assoc my-vec 5 "Hello")
;; => java.lang.IndexOutOfBoundsException: 

my-vec
;; => [1 2 3 4]


(def my-map {:a '1 :b '2 :c '3})
;; => {:a '1 :b '2 :c '3}
(assoc my-map :d '4)
;; => {:a 1, :b 2, :c 3, :d 4}
;; the original map does not change, we are returning new maps
my-map
;; => {:a 1, :b 2, :c 3}
(assoc my-map :a '34)
;; => {:a 34, :b 2, :c 3}

(assoc my-map :b "hello")
;; => {:a 1, :b "hello", :c 3}
;; our map has not changed
my-map
;; => {:a 1, :b 2, :c 3}
;; a key can be called like a function, with the map as the arg
(:a my-map)
1
;; you cannot change the value with update by just providing a new value
(update my-map :b "Hello")
;; => java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn
(update my-map :b '33)
;; => java.lang.ClassCastException: java.lang.Long cannot be cast to clojure.lang.IFn
;; you can use a function, but not the normal notation
(update my-map :b (+ 2 33))
;; => java.lang.ClassCastException: java.lang.Long cannot be cast to clojure.lang.IFn
;; call a function without args, it will use the current value as an arg
(update my-map :b inc)
{:a 1, :b 3, :c 3}
;; our map is still the same
my-map
;; => {:a 1, :b 2, :c 3}
;; update b by sending the + function with args 2 and 33, like "apply"
;; => (update my-map :b + 2 33)
{:a 1, :b 37, :c 3}

 

You’re welcome.

There are 286 words in this article.