Collection of Clojure has linear list, tree, map (hash table), set, and vector type. You cannot do destructive assignment or modification to the collection. Instead, Clojure creates a new copy for you, however, the contents of the collection are shared with the original one and the copied one.
user=> (let [my-vector [1 2 3 4] my-map {:fred "ethel"} my-list (list 4 3 2 1)] (list (conj my-vector 5) (assoc my-map :ricky "lucy") (conj my-list 5) my-vector my-map my-list)) ([1 2 3 4 5] {:ricky "lucy", :fred "ethel"} (5 4 3 2 1) [1 2 3 4] {:fred "ethel"} (4 3 2 1)) Vector is as same as #(a b c ...) of Scheme but not std::vector of C++.
There is a map function.
user=> (map #(+ % 3) [2 4 7]) [5 7 10] Any data can have metadata.
user=> (def v [1 2 3]) user=> (def attributed-v (with-meta v {:source :trusted})) user=> (:source (meta attributed-v)) :trusted user=> (= v attributed-v) true The collection has common interface as Java does. Let's try first and rest, which are parts of seq interface.
user=> (let [my-vector [1 2 3 4] my-map {:fred "ethel" :ricky "lucy"} my-list (list 4 3 2 1)] [(first my-vector) (rest my-vector) (keys my-map) (vals my-map) (first my-list) (rest my-list)]) [1 (2 3 4) (:ricky :fred) ("lucy" "ethel") 4 (3 2 1)] The collection who has seq interface is called sequence.
References:
http://clojure.org/functional_programming
http://java.ociweb.com/mark/clojure/article.html | コレクションには線形リスト,木の他に,マップ(ハッシュテーブル),集合,ベクタがあります.コレクションに対する破壊的代入,変更はできません.代わりに新しいコレクションが作られますが,新しいコレクションと古いコレクションはデータを共有します. user=> (let [my-vector [1 2 3 4] my-map {:fred "ethel"} my-list (list 4 3 2 1)] (list (conj my-vector 5) (assoc my-map :ricky "lucy") (conj my-list 5) my-vector my-map my-list)) ([1 2 3 4 5] {:ricky "lucy", :fred "ethel"} (5 4 3 2 1) [1 2 3 4] {:fred "ethel"} (4 3 2 1)) ベクタはSchemeで言うベクタ #(a b c ...) のことであり,C++のstd::vectorとは違う概念です. map関数があります. user=> (map #(+ % 3) [2 4 7]) [5 7 10] すべてのデータはメタデータを持つことができます. user=> (def v [1 2 3]) user=> (def attributed-v (with-meta v {:source :trusted})) user=> (:source (meta attributed-v)) :trusted user=> (= v attributed-v) true コレクションはJavaのように共通のインタフェースを持ちます.seqインタフェースのfirstとrestを使ってみましょう. user=> (let [my-vector [1 2 3 4] my-map {:fred "ethel" :ricky "lucy"} my-list (list 4 3 2 1)] [(first my-vector) (rest my-vector) (keys my-map) (vals my-map) (first my-list) (rest my-list)]) [1 (2 3 4) (:ricky :fred) ("lucy" "ethel") 4 (3 2 1)] seqインタフェースを持つコレクションをシーケンスと呼びます. 参考 http://clojure.org/functional_programming http://java.ociweb.com/mark/clojure/article.html |
Education > Closer to Clojure >