In clojure, to edit the values of the keys of a map, there are 2 options available:
updateassocThe only difference that I could find from the clojure documentation is that the update function does the following extra thing:
If the key does not exist, nil is passed as the old value.
Are there any specific use cases where in I should use update or assoc other than this?
Or in which cases I should prefer what (If I have missed these use cases).
They both state clear intent in your code when used properly:
assoc hints to the reader, that new kv-pairs are added (or
replacing the values for existing keys) and that they tend to not be
relying on the current values for that keys.update hints, that one value for a key gets updated and the original
value (if present) maybe used for this calculation.(update {} :a (fnil inc 0))
; → {:a 1}
(update {:a 41} :a (fnil inc 0))
; → {:a 42}
(assoc {:z 0} :a 42 :b 23}
; → {:z 0, :a 42, :b 23}
You an emulate update with assoc as follows
(assoc m :foo (f (:foo m)))
which looks clunky and is better off as:
(update m :foo f)
which returns a new map with f applied on the the value corresponding to the :foo key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With