swap-pairs, p86
user=> (apply list (range 10))
(0 1 2 3 4 5 6 7 8 9)
user=> (drop 1 (apply list (range 10)))
(1 2 3 4 5 6 7 8 9)
user=> (take-nth 2 (drop 1 (apply list (range 10))))
(1 3 5 7 9)
user=> (take-nth 2 (apply list (range 10)))
(0 2 4 6 8)
user=> (interleave '(1 3 5 7 9) '(0 2 4 6 8))
(1 0 3 2 5 4 7 6 9 8)
user=> (def list1 (take-nth 2 (drop 1 (apply list (range 10)))))
#'user/list1
user=> (def list2 (take-nth 2 (apply list (range 10))))
#'user/list2
user=> (def empty-list (empty (apply list (range 10))))
#'user/empty-list
user=> (def total-list (interleave list1 list2))
#'user/total-list
user=> (into empty-list total-list)
(8 9 6 7 4 5 2 3 0 1)
map-map, p86
hash-map is unsorted collections, while sorted-map is sorted. So you can see the output of the hash-map is unsorted, while that of sorted-map is sorted.
The synopsis of "for" is "(for [k1 v1 k2 v2 ...] (return-value))". So when f is inc, m is (hash-map :z 5 :c 6 :a 0), to "(for [[k v] m] [k (f v)])", [k v] is [:z 5], [:c 6] and [":a" 0], and the return value is "[k (f v)]", thus [:z (inc 5)], [:c (inc 6)] and [:a (inc 0)].
seq function, p87
"seq" function produces a sequence over its argument. But the exact type is different based on the type of its arguments:
user=> (type (seq '(1 3 2)))
clojure.lang.PersistentList
user=> (type (seq [1 3 2]))
clojure.lang.PersistentVector$ChunkedSeq
user=> (type (seq {:a 1 :b 2}))
clojure.lang.PersistentArrayMap$Seq
user=> (type (seq #{1 3 2}))
clojure.lang.APersistentMap$KeySeq
user=> (type (seq nil))
nil
destructuring a lazy seq, p95
(let [[x & rest] (random-ints 50)] (str (str x) " - " (str (first rest)) " - " (second rest)))
realizing random number
realizing random number
realizing random number
"23 - 37 - 10"
reduce-by, p118
See Notes of "reduce-by" in "Clojure Programming" ;
pprint
can be used directly in clojure repl.
If you want use it in a script, write your namespace declaration like this:
(ns startclojure.core (:require clojure.pprint))
Then you can use it as (clojure.pprint/pprint val)
.
assoc-in, get-in vs assoc, get, p120
=> (assoc-in {} [:a :b] 321)
{:a {:b 321}}
=> (assoc {} [:a :b] 321)
{[:a :b] 321}
=> (get-in {:a {:b 321}} [:a :b])
321
=> (get {:a {:b 321}} [:a :b])
nil
=> (get {[:a :b] 321} [:a :b])
321
=> ({[:a :b] 321} [:a :b])
321
=> (get-in {[:a :b] 321} [:a :b])
nil
=> (get-in {:a 23} :a)
IllegalArgumentException ...
=> (get {:a 23} :a)
23