The first Clojure - 04.Maps, Sequences

A map is a secuence of key-value pairs. The keys can be pretty much any kind of object and a vlue can be looked up inside a map with its key.

(def the-map {:a 1 :b 2 :c 3})
;=> #'user/the-map

The values can be looked up like this:
(the-map :b)
;=> 2

(:b the-map)
;=> 2

Return a default value if not found.
(:z the-map 26)
;=> 26

assoc and dissoc

(def updated-map (assoc the-map :d 4))
;=> #'user/updated-map
;=> {:d 4, :a 1, :b 2, :c 3}
(dissoc updated-map :a)
;=> {:b 2, :c 3, :d 4}

=> (def users {:kyle {
  :date-joined "2009-01-01"
  :summary {
  :average {
  :monthly 1000
  :yearly 12000}}}})

If you wnated to update Kyle’s summary for his monthly average, you couldn’t simply drill down to the spot on the map and update it in place as you would in most other languages.
Fortunately, Clojure provides three functions that make update nested collections easy.

(assoc-in map [key & more-keys] value)

=> users
{:date-joined "2009-01-01",
  {:monthly 1000, :yearly 12000}}}}
=> (assoc-in users [:kyle :summary :average :monthly] 3000)
{:date-joined "2009-01-01",
  {:monthly 3000, :yearly 12000}}}}

Read values out of such nested maps.
(get-in users [:kyle :summary :average :monthly])
;=> 1000

Update values in such nested maps. To see it in action, imageineyou wanted to increase Keyle’s monthly average by 500

=> (update-in users [:kyle :summary :average :monthly] + 500)
{:date-joined "2009-01-01",
  {:monthly 1500, :yearly 12000}}}}

A seauence isn’t a collection type. Rather, a sequence is an interface (called ISeq) that expose a “one thing followed by more things” abstraction.
The sequence abstraction allows all data structures to look and act like lists, even if the underlying values are some other collection type (such as a vector or hash map) or are even created laxily as they’re needed.
The ISeq interface provides three functions: first, rest and cons.

(first (list 1 2 3))
;=> 1
(rest (list 1 2 3))
;=> (2 3)
(first [1 2 3])
;=> 1
(rest [1 2 3])
;=> (2 3)
(first {:a 1 :b 2})
;=> [:b 2]
(rest {:a 1 :b 2})
;=> ([:a 1])
(first [])
;=> nil
(rest [])
;=> ()

first returns the first element of the sequence like peek does for lists but the same
way on all collection types. rest returns the sequences without the first element just
like pop does on lists but the same way on all collection types and without throwing an
exception for empty things.
cons (short for construct) creates new sequences given an element and an existing
(cons 1 [2 3 4 5])

;=> (1 2 3 4 5)


이 블로그의 인기 게시물

Android Service에서 AlertDialog 띄우기

MongoDB, 설치와 간단 사용법

Android Thread 내에서 UI 핸들링