學習 Clojure/資料結構
外觀
集合是一個不包含重複項的集合。 Clojure 有兩種集合型別
- 雜湊集被實現為雜湊對映,因此具有(近乎)恆定的查詢、插入和刪除時間。
- 排序集被實現為有序二叉樹,因此具有對數查詢、插入和刪除時間。
讀取器識別雜湊集的文字語法
#{67 2 8.8 -78} ; a hash set of four numbers
許多序列函式生成惰性序列,它們不是由自身資料支援的序列:惰性序列的項是按需從函式生成或從其他來源(例如另一個集合)檢索的。例如,代表預先存在的向量的前 8 項的序列可以是惰性的,因為不需要複製項:如果我們說請求惰性序列的第 3 項,我們將得到向量的第 3 項。
基於函式的惰性序列根據傳遞給函式的索引生成項。由於此類序列根本沒有實際資料支援,因此它們可以是無限的。例如,函式cycle返回一個惰性序列,代表另一個序列的無休止重複
(cycle [1 2 3]) ; returns a lazy sequence of 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3... etc.
[嗯,在什麼情況下惰性序列會保留生成的項?我假設迴圈不會最終由一個巨大的實際列表或向量支援,但doseq似乎保留了生成的的值。哪些其他情況與doseq類似?]
Clojure 所謂的structmap(如“結構對映”)僅僅是持久雜湊對映的變體,但其中預定義的鍵集具有最佳化的儲存和查詢。
Structmap 是透過首先呼叫clojure/create-struct 來定義稱為基礎的藍圖而建立的。然後使用函式clojure/struct-map 使用基礎建立實際的 structmap
(def george (create-struct :apple :banana :orange))
(struct-map george :apple 3 :banana 9 :orange 12) ; create a structmap with the key-val pairs :apple => 3, :banana => 9, and :orange => 12
(struct-map george :banana 9 :apple 3 :orange 12) ; notice the key order need not be that used in create-struct
(struct-map george :apple 3 :orange 12) ; the key :banana is not specified, so its value defaults to nil
您可以透過僅使用clojure/struct 指定鍵的值來建立 structmap
(struct george -87 0 9) ; keys implied by their order in create-struct, so this is :apple => -87, :banana => 0, :orange => 12