Learn clojure in Y minutes - Maps

The following is from Learn clojure in Y minutes.

array maps and hash maps share the map interface.

array maps - less fast lookup, retains key order

hash maps - fast lookup, doesn't retain key order

> (class {:a 1 :b 2 :c 3})
    clojure.lang.PersistentArrayMap
    
    > (class (hash-map :a 1 :b 2 :c 3))
    clojure.lang.PersistentHashMap

Array maps eventually become hash maps after they get sufficiently large.

keyword - like strings, but with efficiency bonuses

Maps can use any hashable type as a key, but usually keywords are best.

> (class :a)
    clojure.lang.Keyword
    
    > (def stringmap {"a" 1 "b" 2 "c" 3})
    #'learn-clojure.core/stringmap
    
    > (def keymap {:a 1 :b 2 :c 3})
    #'learn-clojure.core/keymap

Note: Commas in a map are treated the same as whitespace.

You can retrieve a value from a map by calling it as a function.

> (stringmap "a")
    1
    
    > (keymap :b)
    2

This operation is commutative with keywords, but not with strings.

> (:b keymap)
    2

Note: A non-existent key in a map yields nil.

assoc - used to add new keys to hash maps

dissoc - used to remove keys from hash maps

> (def newkeymap (assoc keymap :d 4))
    #'learn-clojure.core/newkeymap
    
    > newkeymap
    {:c 3, :b 2, :d 4, :a 1}
    
    > (dissoc keymap :b)
    {:b 2, :a 1}

Don't forget that clojure types are immutable.

> keymap
    {:c 3, :b 2, :a 1}

Published January 07, 2015