Today I will look at Maps, one of the most important collection types in Clojure. Maps are collections of key-value pairs. Keys can be of any type in Clojure including functions, lists, other maps etc. The are 3 types of maps in Clojure: Hash Maps, Sorted Maps and Array Maps. Sorted maps keep the key value pairs in a certain order which implies that a lookup time may not be constant and it also allows you to traverse the values in the order of the keys. Sorted maps have a constraint in that the keys have to be comparable.
You can create them as follows
; Hash maps
{"number" 1 2 2.25 :pi 22/7}
=> {"number" 1, 2 2.25, :pi 22/7}
or alternatively
(hash-map "number" 1 2 2.25 :pi 22/7)
=> {:pi 22/7, "number" 1, 2 2.25}
;Sorted maps
(sorted-map "number" 1 "2" 2.25 "pi" 22/7)
=> {"2" 2.25, "number" 1, "pi" 22/7} ; note the order
; you can also sort using a custom comparator
(sorted-map-by #(< (count %1) (count %2))
"number" 1 "2" 2.25 "pi" 22/7)
=> {"2" 2.25, "pi" 22/7, "number" 1}
You can lookup values as follows
(get {"number" 1 2 2.25 :pi 22/7} :pi)
=> 22/7
or alternatively use the key as a function
(:pi {"number" 1 2 2.25 :pi 22/7})
=> 22/7
if you don't find the key
(get {"number" 1 2 2.25 :pi 22/7} :missing)
=> nil
You can add new key value pairs as follows
(assoc {"number" 1 2 2.25 :pi 22/7} :association {:a 2.00 :b 5.78})
=> {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}}
You can remove key value pairs as follows
(dissoc {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}} :pi )
=> {"number" 1, 2 2.25, :association {:a 2.0, :b 5.78}}
You can get a list of all the keys as follows
(keys {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}})
=> ("number" 2 :pi :association)
You can also get all the values as follows
(vals {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}})
=> (1 2.25 22/7 {:a 2.0, :b 5.78})
You can also combine maps as follows
(merge {"2" 2.25, "number" 1, "pi" 22/7} {"number" 1, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}})
=> {"2" 2.25, "number" 1, "pi" 22/7, 2 2.25, :pi 22/7, :association {:a 2.0, :b 5.78}}
That's all for today, tomorrow I will move onto Sets
(println "Bye 4 Now!!")
No comments:
Post a Comment