Exercise 06 Maps - MikeyYeahYeah/clojure-koans GitHub Wiki
Exercise 06 - Maps
Creating a a Map
You can create a map in clojure by:
- {:a 1 :b 2}
- (hash-map :a 1 :b 2)
Working with Maps
Count will count the number of sets
(count {:a 1 :b 2})
;;=> 2
You lookup the value of assigned to a key
(get {:a 1 :b 2} :b)
;;=> 2
You can also use a map as a function to grab a value assigned to a key
({:a 1 :b 2} :a)
;;=> 1
You can also use a keywords and non-keywords as a function to grab a value from an assigned key
(:a {:a 1 :b 2})
;;=> 1
({2010 "Vancouver" 2014 "Sochi" 2018 "PyeongChang"} 2014)
;;=> "Sochi"
If a key can't be found, a nil is returned. However, you can create your won default value for a missing key
(get {:a 1 :b 2} :c)
;;=> nil
(get {:a 1 :b 2} :c :key-not-found)
;;=> :key-not-found
You can see if a key exists or doesn't exist using contains? (Boolean Returned)
(contains? {:a nil :b nil} :b)
;;=> true
(contains? {:a nil :b nil} :c)
;;=> false
Maps are Immutable AKA can't be changed. You can create cheap copies though!
You can easily add items by creating a new copy using assoc
(assoc {:monday "Pizza"} :tuesday "Burgers")
;;=> {:monday "Pizza" :tuesday "Burgers"}
And replace values in a a matching key
(assoc {:monday "Pizza :tuesday "Burgers"} :tuesday "Indian")
;;=> {:monday "Pizza" :tuesday "Indian"}
Or remove a key/value pair using dissoc
(dissoc {:a "alpha" :b "beta"} :b)
;;=> {:a "alpha"}
While we are at it, lets combine to maps using merge
(merge {:a "alpha" :b "beta"} {:c "charlie" :d "delta"})
;;=> {:a "alpha" :b "beta" :c "charlie" :d "delta"}
Note: If you are trying to add multiple versions of the same key, the right most wins.
(merge {:a 1} {:a 2} {:a 3})
;;=> {:a 3}
Now let's get fancy! You can use merge-with to decide how to handle matching keys
(merge-with +
{:a 99 :b 48 :c 63}
{:a 1 :b 2 :c 7})
;;=> {:a 100 :b 50 :c 70}
You can pull all keys or values from a map but the order is not reliable. You should pass it into a function that handles the order like sort
Note: Returned as a sequence
(sort(keys {:a 1 :c 2 :b 3}))
;;=> (:a :b :c)
(sort (vals {:a 10 :b 50 :c 40}))
;;=> (10 40 50)