創(chuàng)建數(shù)據(jù)結(jié)構(gòu)
創(chuàng)建方法如下:
(list 1 2 3) ; ? '(1 2 3)
(vector 1 2 3) ; ? [1 2 3]
(hash-map :a 1 :b 2) ; ? {:a 1 :b 2}
(hash-set :a :b :c) ; ? #{:a :b :c}
數(shù)據(jù)結(jié)構(gòu)在vector锚沸,map和set的互轉(zhuǎn)
(def my-vec [1 2 3])
(set my-vec) ; ? #{1 2 3}
(def my-map {:a 1 :b 2})
(vec my-map) ; ? [[:a 1] [:b 2]]
(flatten (vec my-map)) ; ? (:a 1 :b 2)
(set my-map) ; ? #{[:b 2] [:a 1]}
(def my-set #{:a :b :c :d})
(vec my-set) ; ? [:a :c :b :d]
;; And for fun:
(zipmap [:a :b :c] [1 2 3]) ; ? {:c 3 :b 2 :a 1}
(apply hash-map [:a 1 :b 2]) ; ? {:a 1 :b 2}
這里有一個(gè)簡(jiǎn)寫的列表
literal long name short name
------- --------- ------------------
() list *{no short name}*
[] vector vec
{} hash-map *{no short name}*
#{} hash-set set
怎么使用數(shù)據(jù)結(jié)構(gòu)
;; Vectors
(def v [:a :b :c])
(nth v 1) ; ? :b
(v 1) ; ? :b (same)
(first v) ; ? :a
(rest v) ; ? (:b :c)
(next v) ; ? (:b :c)
(last v) ; ? :c
;; Lists
;; Same as vectors, but can't index.
;; Maps
(def m {:a 1 :b 2})
(get m :a) ; ? 1
(m :a) ; ? 1 (same)
(:a m) ; ? 1 (same!)
(get m :x 44) ; ? 44 (if no :x, 44 is the default)
(keys m) ; ? (:a :b)
(vals m) ; ? (1 2)
;; Grab a key or a val from a single map entry:
(key (first m)) ; ? :a
(val (first m)) ; ? 1
;; Of course, note that maps are not ordered.
;; Sets
(def s #{:a :b :c})
(s :a) ; ? :a
(s :z) ; ? nil
需要注意是clojure的數(shù)據(jù)結(jié)構(gòu)是不可改變的,如果對(duì)數(shù)據(jù)結(jié)構(gòu)進(jìn)行操作,那么它會(huì)復(fù)制一份新的。
請(qǐng)看如下操作:
;; Vectors
(def v [:a :b :c])
(def li '(:a :b :c))
(conj v :d) ; ? [:a :b :c :d]
(conj li :d) ; ? (:d :a :b :c)
v ; ? is still [:a :b :c]
li ; ? is still (:a :b :c)
;; Maps
(def m {:a 1 :b 2})
(assoc m :c 3) ; ? {:a 1 :c 3 :b 2}
(dissoc m :b) ; ? {:a 1}
m ; ? is still {:a 1 :b 2}
;; Sets
(def s #{:a :b})
(conj s :c) ; ? #{:a :c :b}
(disj s :a) ; ? #{:b}
s ; ? is still #{:a :b}
String的操作
我們之前講過(guò)clojure的namespaces,這里使用require進(jìn)行引入
(str "hi" "there")
;; ? "hithere"
(count "hello")
;; ? 5
(require '[clojure.string :as str])
;; ? nil
(str/split "hello there" #" ")
;; ? ["hello" "there"]
(str/join ["hello" "there"])
;; ? "hellothere"
(str/join " " ["hello" "there"])
;; ? "hello there"
(str/replace "hello there" "ll" "LL")
;; ? "heLLo there"
還有一些操作
(first "hello")
;; ? \h
(last "hello")
;; ? \o
(rest "hello")
;; ? (\e \l \l \o)
(nth "hello" 1)
;; ? \e
(doseq [letter "hello"] (println letter))
;; h
;; e
;; l
;; l
;; o
;; ? nil
值,不變性和持久化(Values, Immutability, and Persistence)
一個(gè)value就是一個(gè)常量污桦,在clojure中,所有的scalars和data structure都是這樣的匙监,不可被改變凡橱,沒(méi)有"遠(yuǎn)處的改變",你可以放心的使用一個(gè)數(shù)據(jù)亭姥,因?yàn)椴挥脫?dān)心這個(gè)數(shù)據(jù)被改變稼钩。如下:
``
(def a [1 2 3 4 5])
(def b a)
;; Do what you will with b
, ...
(my-func a) ; but it won't affect a
.