Clojure's Maps Overview
Maps are fundamental data structures in any clojure program.
They are extremely fast, simple to reason about and very handy.
Declaration of maps
As you may know, maps are a correlation between two clojure ‘object’ and are defined as so:
Let’s notice first that a map must contain an even number of elements, otherwise the reader will let you know.
Also you can use different types of object as your key or values in your map.
In the clojure world we use a lot of :keywords
. They are particular data-type, very similar to string but that fit particularly well into map.
Of course you can assign a name to your map.
One very important thing to notice is that the order of the couple {:key :value}
is not fixed inside a map: in fact if you think about it, it doesn’t make sense for a map to be ordered.
You can find a deeper explaination about how to create maps in the following post:
-
Create Clojure Maps 1/2 : hash-map, array-map, zipmap, sorted-map and sorted-map-by
-
Create Clojure Maps 2/2 : bean, frequencies, group-by, index
Read map
Now that we know how to define a basic map, let’s see how to read the values inside it.
One of the simplest ways to read a value from a map is the function get.
Another and more used way to get values from a map is to use the map itself as a function and the key as an argument.
Finally a very used way to get values out of a map is to use keywords as functions and the map itself as argument.
A deeper explaination about how to read maps can be found here:
- Read Clojure Map 1/2 overview of: get, get-in, contains? and find
- Read Clojure Map 2/2 overview of: keys, vals and select-keys
“Modify” map
As you may know it is not possible to modify a clojure map, since it is immutable.
However you may create new maps with a different number of keys, thus a different number of values.
To add a value into a map, the easiest way is to use the function assoc, that gets the old map, the new keys and the new values as arguments.
In case of conflict assoc
will overwrite the old values.
On the other side it is also very easy to remove keys-values from a map using the function dissoc
.
dissoc
takes the map as input and one or more keys you want to eliminate.
Finally it is possible to merge two different maps using the function merge that takes 2 or more maps as argument and returns one single map.
Please note that the last argument is the one that will be chosen in case of conflict between the keys.
End
This post was just a very quick overview about clojure maps, each of the three points I tackled (declare, read and modify maps) can be expandend quite a lot.
It would be awesome if you guys could comment asking which point you’d rather me to cover next time.