Clojure has two types of maps. The PersistentArrayMap and the PersistentHashMap data types are responsible for key-value collections. The only exception is the PersistentHashSet data type, which looks like #{:key-here :key-here}
. The difference between a Map
and a Set
is that the key is the value in a set, where as a key holds a separate value in a Map
.
The
hash-map
form can be used to make a key-value collection:
user> (def -hmap (hash-map :key1 "value" :key2 "value2")) #'user/-hmap user> (vals -hmap) ("value2" "value") user> (keys -hmap) (:key2 :key1) user> (:key2 -hmap) "value2"
The
array-map
form can do the same:
user> (def -amap (array-map "a" 1 "b" 2)) #'user/-amap user> (keys -amap) ("a" "b")
Remember to use the get
form when needing to set default values for missing keys:
user> (get -amap "a" :not-found) 1 user> (get -amap "c" :not-found) :not-found user> (-hmap :key2) "value2" user> (-hmap :key3) nil user> (-hmap :key3 :not-found...