typestar

Map lookup in Clojure

Tracks seedling counts in a map, then adds, drops, and merges keys.

;; a map literal pairs keys with values
(def shelf {:basil 12 :dill 4 :sorrel 0})

;; get returns nil for a missing key unless you supply a default
(println (get shelf :dill) (get shelf :chervil 0))

;; assoc and dissoc return new maps and leave the original alone
(def restocked (assoc shelf :chervil 6))
(def thinned (dissoc restocked :sorrel))
(println thinned "vs" shelf)

;; merge folds the second map over the first, right side winning
(println (merge shelf {:dill 20 :thyme 3}))

;; contains? asks about keys; some searches the values instead
(println (contains? shelf :sorrel) (some zero? (vals shelf)))

How it works

  1. (get shelf :chervil 0) returns a default instead of nil for a key that is missing.
  2. assoc, dissoc, and merge each build a new map while shelf stays as it was.
  3. contains? asks whether a key is present, while (some zero? (vals shelf)) searches the values.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
611
Tokens
85
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 2 of 3 in Collections, step 5 of 27 in Language basics.

← Previous Next →

Map lookup in other languages