clojure-koans/src/koans/05_maps.clj

51 lines
1.4 KiB
Clojure
Raw Normal View History

(ns koan-engine.runner)
(ns koans.05-maps (:use koan-engine.core))
2010-02-08 04:29:31 +00:00
(meditations
2013-03-04 23:30:00 +00:00
"Don't get lost when creating a map"
(= {:a 1 :b 2} (hash-map :a 1 __ __))
2010-02-08 04:29:31 +00:00
"A value must be supplied for each key"
(= {:a 1} (hash-map :a __))
"The size is the number of entries"
2010-10-29 15:45:47 +00:00
(= __ (count {:a 1 :b 2}))
2010-02-08 04:29:31 +00:00
"You can look up the value for a given key"
(= __ (get {:a 1 :b 2} :b))
2013-03-04 23:30:00 +00:00
"Maps can be used as functions to do lookups"
2010-02-08 04:29:31 +00:00
(= __ ({:a 1 :b 2} :a))
"And so can keywords"
(= __ (:a {:a 1 :b 2}))
"But map keys need not be keywords"
(= __ ({2006 "Torino" 2010 "Vancouver" 2014 "Sochi"} 2010))
"You may not be able to find an entry for a key"
2011-02-03 18:26:58 +00:00
(= __ (get {:a 1 :b 2} :c))
"But you can provide your own default"
(= __ (get {:a 1 :b 2} :c :key-not-found))
2010-02-08 04:29:31 +00:00
"You can find out if a key is present"
(= __ (contains? {:a nil :b nil} :b))
"Or if it is missing"
(= __ (contains? {:a nil :b nil} :c))
2013-03-04 23:33:46 +00:00
"Maps are immutable, but you can create a new and improved version"
2014-04-25 19:11:18 +00:00
(= {1 "January" 2 __} (assoc {1 "January"} 2 "February"))
2010-02-08 04:29:31 +00:00
2013-03-04 23:33:46 +00:00
"You can also create a new version with an entry removed"
2010-02-08 04:29:31 +00:00
(= {__ __} (dissoc {1 "January" 2 "February"} 2))
2013-03-04 23:33:46 +00:00
"Often you will need to get the keys, but the order is undependable"
2010-02-08 04:29:31 +00:00
(= (list __ __ __)
(sort (keys {2010 "Vancouver" 2014 "Sochi" 2006 "Torino"})))
2010-02-08 04:29:31 +00:00
2013-03-04 23:33:46 +00:00
"You can get the values in a similar way"
(= (list __ __ __)
2010-02-08 04:29:31 +00:00
(sort (vals {2006 "Torino" 2010 "Vancouver" 2014 "Sochi"}))))