學習 Clojure/集合函式
外觀
clojure 名稱空間包含許多用於處理集合的函式和宏。我不會重複 API 文件中的參考資訊,只給出一些示例操作。
- (count collection)
返回集合中的專案數量。
(count [a b c]) ; return 3 (count nil) ; return 0
- (conj collection item)
連線。返回一個新的集合副本,其中添加了專案。專案的新增方式取決於集合型別,例如,連線到列表的專案新增到開頭,而連線到向量的專案新增到末尾。
(conj [5 7 3] 9) ; returns [5 7 3 9] (conj (list 5 7 3) 9)) ; returns list (9 5 7 3) (conj nil item) ; returns list (item)
- (list item*)
- (vector item*)
- (hash-map keyval*) 其中 keyval => key value
分別生成列表、向量或雜湊圖。通常你總是可以使用字面語法來代替這些函式,但是擁有函式可以讓我們傳遞給期望函式引數的其他函式。
- (nth collection n)
返回collection中的第n個專案,其中 collection 是任何集合但不是對映。(集合可以是對映上的序列,但不是實際的對映。)
(nth [31 73 -11] 2) ; returns -11 (nth (list 31 73 -11) 0) ; returns 31 (nth [8 4 4 1] 9) ; exception: out of bounds
- 關鍵字作為函式
關鍵字可以用作函式來查詢各種對映(雜湊圖、集合、結構對映等)中鍵的值。
(:velcro {:velcro 5 :zipper 7}) ; returns 5, the value mapped to :velcro in the hashmap
- 對映作為函式
對映型別本身可以用作函式來查詢其鍵的值。
({:velcro 5 :zipper 7} :velcro) ; returns 5, the value mapped to :velcro in the hashmap
({3 "cat" :tim "moose"} :tim) ; returns "moose", the value mapped to :tim in the hashmap
(["hi" "bye"] 1) ; returns "bye", the value of the second index in the vector
大多數序列函式可以傳遞不是序列但可以從中派生序列的物件,例如,可以傳遞列表代替序列。
在序列操作和專門針對特定集合型別操作之間存在冗餘的情況下,冗餘主要出於效能考慮。例如,要生成向量的反向順序序列,可以使用序列操作reverse或特定於向量的rseq:雖然rseq的通用性較低,但效率更高。
- (seq collection)
返回表示集合的序列。seq也適用於原生 Java 陣列、字串,以及任何實現了 Iterable、Iterator 或 Enumeration 的物件。