Lion in a what?

Digital Media, Organizational, and Personal Development

twitter linkedin github gtalk

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})

> (class (hash-map :a 1 :b 2 :c 3))

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)

> (def stringmap {"a" 1 "b" 2 "c" 3})

> (def keymap {:a 1 :b 2 :c 3})

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")

> (keymap :b)

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

> (:b keymap)

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))

> 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}