Clojure入門時のメモ
参考文献
:a
keywordと言われる
そうっぽい
いくつかはコンパイル時用に特殊に使われる
code:data_structure.clj
(list 1 2 3) ; ⇒ '(1 2 3)
(hash-map :a 1 :b 2) ; ⇒ {:a 1 :b 2}
(hash-set :a :b :c) ; ⇒ #{:a :b :c} listとvector何が違うんだ
vector
(def v [:a :b :c])
(nth v 1) ; => :a
(v 1) ; => :a
(first v) ; => :a
(rest v) ; => (:a :b)
[:b :c]じゃないの?SnO2WMaN.icon
(next v) ; => (:b :c)
restと同じという意味で良いのか?SnO2WMaN.icon
(last v) ; => :c
(conj v :d) ; => [:a :b :c :d]
ただしvは依然[:a :b :c]であることに注意!Immutableである
hash-map
(def m {:a 1 :b 2})
(get m :a) ; => 1
(m :a) ; => 1
(:a m) ; => 1
(get m :x 44) ; => 1
デフォルト値
(keys m) ; => (:a :b)
(key (first m)) ; => :a
(vals m) ; => (1 2)
(val (first m)) ; => 1
(assoc m :c 3) ; => {:a 1 :c 3 :b 2}
順番はわからない
生成することに注意
dissoc m :b ; => {:a 1}
sets
略
文字列操作
(str "hi" "there") ; => "hithere"
(count "hi") ; => 2
以下,(require '[clojure.string :as str])
keywordを予約語:asっぽく使えるんだSnO2WMaN.icon
clojure.stringをstrとエイリアスを与える
(str/split "hello there" #" ") ; => ["hello" "there"]
(str/join ["hello" "there"]) ; => "hellothere"
seq
true/false
falseであるもの(falsy)
nilとfalse
その他全部がtrulyである
等価性
ディープにやる
つまり(= {:a [1,2]} {:a '(1,2)}) ; => true
数値について型違いでも等価か判断するには==
(= 4 4.0) ; => false
(== 4 4.0) ; => true
map
(map inc [10 20 30])
;; (11 21 31)
(map (fn [x] (+ x 1)) [10, 20, 30])と同等
(map (fn [x y] (str x y)) [:a :b :c] [1 2 3])
;; (":a1" ":b2" ":c3")
最も短いものに切り詰められる,つまり
(map (fn [x y] (str x y)) [:a :b] [1 2 3])
;; (":a1" ":b2")
range
(range 10) ; (0,1,2,3,4,5,6,7,8,9)
filter
(filter odd? (range 10))
;; (1,3,5,7,9)
ところで,(odd? 1) ; => true
for
(for [i (range 10)] i)
;; (0,1,2,3,4,5,6,7,8,9)
(for [i (range 10)] (* i i))
;; (0,1,4,9,16,...,81)
(for [i (range 10) :when (odd? i)] [i (str "<" i ">")])
;; ([1,"<1>"] [3 "<3>"] ... [9 "<9>"])
reduce
reduce + [1 2 3 4 5]
;; 15
評価順
1 + 2 [3 4 5]
3 + 3 [4 5]
6 + 4 [5]
10 + 5 []
15
その他いくつかのフロー制御
when
ifのそうでない場合をカット(nilを返却)
(when (neg? x) (throw (RuntimeException. (str "x must be positive: " x))))
defn
多分だが
defn hoge "Some doc here" [x, y] (+ x y)
ドキュメントを挟むことが出来る