2015-09-13 05:28:39 +00:00
|
|
|
(ns koans.06-maps
|
2015-10-17 04:13:25 +00:00
|
|
|
(:require [koan-engine.core :refer :all]))
|
2014-01-26 00:04:22 +00:00
|
|
|
|
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"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= {:a 1 :b 2} (hash-map :a 1 :b 2))
|
2010-09-30 12:14:07 +00:00
|
|
|
|
2010-02-08 04:29:31 +00:00
|
|
|
"A value must be supplied for each key"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= {:a 1} (hash-map :a 1))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
|
|
|
|
"The size is the number of entries"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= 2 (count {:a 1 :b 2}))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
|
|
|
|
"You can look up the value for a given key"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= 2 (get {:a 1 :b 2} :b))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
2013-03-04 23:30:00 +00:00
|
|
|
"Maps can be used as functions to do lookups"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= 1 ({:a 1 :b 2} :a))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
|
|
|
|
"And so can keywords"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= 1 (:a {:a 1 :b 2}))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
|
|
|
|
"But map keys need not be keywords"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= "Sochi" ({2010 "Vancouver" 2014 "Sochi" 2018 "PyeongChang"} 2014))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
|
|
|
|
"You may not be able to find an entry for a key"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= nil (get {:a 1 :b 2} :c))
|
2011-02-03 18:26:58 +00:00
|
|
|
|
|
|
|
|
"But you can provide your own default"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= :key-not-found (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"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= true (contains? {:a nil :b nil} :b))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
|
|
|
|
"Or if it is missing"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= false (contains? {:a nil :b nil} :c))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
2013-03-04 23:33:46 +00:00
|
|
|
"Maps are immutable, but you can create a new and improved version"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= {1 "January" 2 "February"} (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"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= {1 "January"} (dissoc {1 "January" 2 "February"} 2))
|
2010-02-08 04:29:31 +00:00
|
|
|
|
2013-03-04 23:33:46 +00:00
|
|
|
"Often you will need to get the keys, but the order is undependable"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= (list 2010 2014 2018)
|
2014-11-26 22:01:18 +00:00
|
|
|
(sort (keys { 2014 "Sochi" 2018 "PyeongChang" 2010 "Vancouver"})))
|
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"
|
2015-10-17 04:13:25 +00:00
|
|
|
(= (list "PyeongChang" "Sochi" "Vancouver")
|
|
|
|
|
(sort (vals {2010 "Vancouver" 2014 "Sochi" 2018 "PyeongChang"}))))
|