Keywords & symbols in Clojure
Reads a mixtape track from a map with keywords, then contrasts one with a quoted symbol.
;; keywords evaluate to themselves, which makes them good map keys
(def track {:title "Sea Change" :artist "Wren" :minutes 4})
;; a keyword called as a function looks itself up in a map
(println (:artist track) "-" (:title track))
;; a second argument is the fallback when the key is missing
(println "bpm:" (:bpm track 120))
;; a namespaced keyword keeps keys from colliding across sources
(def tagged (assoc track :mixtape/side :a))
(println (:mixtape/side tagged))
;; a symbol names something else; quoting one stops the lookup
(def side 'flip)
(println (type :a) (type side))
How it works
(:artist track)calls a keyword as a function so it looks itself up in the map.(:bpm track 120)supplies a fallback for a key the map does not carry.:mixtape/sideshows a namespaced key, and(def side 'flip)binds a symbol sotypecan tell the two apart.
Keywords and builtins used here
assocdefprintlntype
The run, in numbers
- Lines
- 16
- Characters to type
- 583
- Tokens
- 71
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 57 seconds.
Step 3 of 3 in Values & bindings, step 3 of 27 in Language basics.