Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should update be preferred over assoc?

In clojure, to edit the values of the keys of a map, there are 2 options available:

  1. update
  2. assoc

The 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).

like image 252
Deepak Tatyaji Ahire Avatar asked Oct 21 '25 14:10

Deepak Tatyaji Ahire


2 Answers

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}
like image 144
cfrick Avatar answered Oct 23 '25 06:10

cfrick


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.

like image 21
Samuel Chase Avatar answered Oct 23 '25 07:10

Samuel Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!