Module 6

More Data Structures

Maps

map

Maps

{:firstname "Sally", :lastname "Brown", :job "programmer"}
{:a 1, :b "two"}
{}
  • Similar to comments, commas are ignored by REPL

Map functions

(map? {:firstname "Sally" :lastname "Brown"})
;;=> true

(get {:firstname "Sally" :lastname "Brown"} :firstname)
;;=> "Sally"

(get {:firstname "Sally"} :lastname :MISS)
;;=> :MISS

More map functions

(assoc {:firstname "Sally"} :lastname "Brown")
;;=> {:firstname "Sally", :lastname "Brown"}

(dissoc {:firstname "Sally" :lastname "Brown"} :lastname)
;;=> {:firstname "Sally"}

(merge {:firstname "Sally"} {:lastname "Brown"})
;;=> {:firstname "Sally", :lastname "Brown"}

(count {:firstname "Sally" :lastname "Brown"})
;;=> 2

Even more map functions

(keys {:firstname "Sally" :lastname "Brown"})
;;=> (:firstname :lastname)

(vals {:firstname "Sally" :lastname "Brown"})
;;=> ("Sally" "Brown")

Maps and keywords

(:firstname {:firstname "Sally" :lastname "Brown"})
;;=> "Sally"

(:lastname {:firstname "Sally"})
;;=> nil

(:lastname {:firstname "Sally"} :MISS)
;;=> :MISS

Exercise: Modeling yourself

Make a map representing yourself. Make sure it contains your first name and last name. Then, add your hometown to the map using assoc or merge.

Collections of collections

[{:name "Mercury"}
 {:name "Venus"}
 {:name "Earth" :moons ["The Moon"]}
 {:name "Mars" :moons ["Phobos" "Deimos"]}
 {:name "Jupiter"
  :moons ["Ganymede" "Callisto" "Io" "Europa"]}]

Exercise: Get the names of people

Create a function called get-names that takes a vector of maps of people and returns a vector of their names.
(get-names [{:firstname "Margaret" :lastname "Atwood"}
            {:firstname "Doris" :lastname "Lessing"}
            {:firstname "Ursula" :lastname "Le Guin"}
            {:firstname "Alice" :lastname "Munro"}])

;;=> ["Margaret Atwood" "Doris Lessing"
;;    "Ursula Le Guin" "Alice Munro"]
Hint: First, create a function that returns the name when given a single person's map.

Exercise: Modeling your classmates

  1. Take the map from a recent exercise -- the one about you.
  2. Find two or three classmates. Ask their name and hometown. Make a vector of maps with their information.
  3. Then, add your information to their information using conj.