跳轉至內容

學習 Clojure/解構

來自華夏公益教科書,開放的書籍,開放的世界

特殊形式 letloopfn 實際上是宏:真正的特殊形式分別命名為 let*loop*fn*。宏最常用於代替實際的特殊形式,因為宏添加了一個名為 解構 的便利功能。

通常,函式期望接收一個集合引數,它打算使用該集合中的特定專案

; return the sum of the 1st and 2nd items of the sequence argument
(defn foo [s]
   (+ (first s) (frest s))) ; sum the first item and the "frest" (first of the rest) item

提取我們想要的值可能變得非常冗長,但在許多情況下,使用解構可以提供幫助

; return the sum of the 1st and 2nd items of the sequence argument
(defn foo [s]
  (let [[a b] s]
    (+ a b)))

在上面,通常在引數列表中指定引數名稱的地方,我們放置一個向量,後跟引數名稱:傳遞給引數 s 的集合中的專案根據位置繫結到向量中的 ab 名稱。類似地,我們可以使用對映進行解構

(def m {:apple 3 :banana 5})
(let [{x :apple} m]            ; assign the value of :apple in m to x
   x)                          ; return x

[我必須說這對我來說感覺很奇怪:難道不應該是 (let [{:apple x} m] x) 嗎?我喜歡將解構表示式看作是映象被解構的集合。]

解構還可以用於提取集合內集合的值。Hickey 在 這裡 給出了更完整的介紹。

華夏公益教科書