Maps in Clojure
Maps are Clojure’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the hash-map
function or the {}
syntax.
(def m {})
Set key/value pairs using typical assoc
.
(def m (assoc m "k1" 7 "k2" 13))
Printing a map using println
will show all of its key/value pairs.
(println "map:" m)
Get a value for a key with (get map key)
.
(def v1 (get m "k1"))
(println "v1:" v1)
If the key doesn’t exist, the zero value of the value type is returned.
(def v3 (get m "k3" 0)) ; The default value (0) is provided
(println "v3:" v3)
The count
function returns the number of key/value pairs when called on a map.
(println "len:" (count m))
The dissoc
function removes key/value pairs from a map.
(def m (dissoc m "k2"))
(println "map:" m)
To remove all key/value pairs from a map, you can simply create a new, empty map.
(def m {})
(println "map:" m)
The optional second return value when getting a value from a map via destructuring indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0
or ""
.
(let [[_ prs] (find m "k2")]
(println "prs:" (boolean prs)))
You can also declare and initialize a new map in the same line with this syntax.
(def n {"foo" 1 "bar" 2})
(println "map:" n)
Clojure provides several useful functions for working with maps in the core library.
(def n2 {"foo" 1 "bar" 2})
(if (= n n2)
(println "n == n2"))
Note that maps appear in the form {"k" v, "k" v}
when printed with println
.
$ clojure -m your-namespace
map: {"k1" 7, "k2" 13}
v1: 7
v3: 0
len: 2
map: {"k1" 7}
map: {}
prs: false
map: {"bar" 2, "foo" 1}
n == n2