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)

댓글 없음:

댓글 쓰기

블록체인 개요 및 오픈소스 동향

블록체인(block chain) 블록체인은 공공 거래장부이며 가상 화폐로 거래할때 발생할때 발생할 수 있는 해킹을 막는 기술. 분산 데이터베이스의 한 형태로, 지속적으로 성장하는 데이터 기록 리스트로서 분산 노드의 운영자에 의한 임의 조작이 불가...