2016년 4월 8일 금요일

The first Clojure - 04.Maps, Sequences

Maps
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
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}}}})
#'Maps/users

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.

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

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

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

update-in
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)
{:kyle
{:date-joined "2009-01-01",
 :summary
 {:average
  {:monthly 1500, :yearly 12000}}}}

Sequences
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
sequence:
(cons 1 [2 3 4 5])

;=> (1 2 3 4 5)

댓글 없음:

댓글 쓰기

ETL 솔루션 환경

ETL 솔루션 환경 하둡은 대용량 데이터를 값싸고 빠르게 분석할 수 있는 길을 만들어줬다. 통계분석 엔진인 “R”역시 하둡 못지 않게 관심을 받고 있다. 빅데이터 역시 데이터라는 점을 볼때 분산처리와 분석 그 이전에 데이터 품질 등 데이...