Map transformation in clojure 1/2
Here it’s another chapter of the series about clojure map.
For those who missed the previous chapter:
Let’s keep going in our journey about clojure map.
In the next chapters I am going to talk about how to modify clojure maps.
As you may know in Clojure we usually don’t “modify” anything but we rather return a new value.
Let’s explore what function clojure.core gives us to modify maps.
The easiest function to start with is definitely
Given a map, a key and a value
assoc(ciate) add the key and the respective value to the map.
As you may guess
assoc can take more than just a couple of
It is important is that you don’t forget to provide an even number of argument after the map.
You may also wonder what happens if you try to
assoc to an already existing key.
As we can see
assoc will reset (update) the old value to the new one.
assoc is a perfectly legitimate way to update old values in a clojure map.
assoc will make our maps bigger
will make them smaller.
As you may have already guessed
dissoc(ciate) will remove a map entry from our maps.
It works exactly like
If you pass more arguments it will remove more map entries
Also note that
dissoc a not existing key is a valid behavior, dissoc will eliminate the map entry, which does not exist and will return the (not) updated map.
Another very useful function is
merge which, as you may have guessed, merge two or more different maps into one.
merge is very simple to reason about, but there is a little detail to keep in mind.
What happens if there is a key collision (if we try to merge two maps with some keys in common) ?
Fortunately this case is documented and made clear in the spec.
In case of key collision the resulting element will be the later to appear.
In the next chapter we are going to explore some function a little more complex, function such as
As always stay tuned and for any question please don’t hesitate to write me or to comment bellow.