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
(get shelf :chervil 0)returns a default instead of nil for a key that is missing.assoc,dissoc, andmergeeach build a new map whileshelfstays as it was.contains?asks whether a key is present, while(some zero? (vals shelf))searches the values.
Keywords and builtins used here
assocdefdissocgetmergeprintlnsomevals
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.
Step 2 of 3 in Collections, step 5 of 27 in Language basics.