Clojure(2) - Special Forms and Deconstruction(1)

Special forms are Clojure’s primitive building blocks of computation, on top of which all the rest of Clojure is built.

1. quote:

quote 的功能是定義一串不被轉譯的代碼,想要轉譯時可以透過 eval 執行。

(def x `(+ 3 4))
(println x)
(println (eval x)) ;; 7

2. do:

do 類似 C 的 {},可以用來定義 code block。

例如我們可以在 do 中執行多個語句:

(do
  (def msg "Inside do form")
  (println msg)
  (println msg))

3. let:

let 可以用來定義 locals。

下面 x2 和 y2 分別為 x 和 y 的平方,計算後回傳距離:

(defn dist
  [x y]
  (let [x2 (* x x)
        y2 (* y y)]
    (Math/sqrt (+ x2 y2))))
  
(println (dist 3 4))

4. destructuring a vector with let:

Clojure 中 collections 的寫法如下:

'(10 "Hola" 12.5) ;; list

[10 "Hola" 12.5] ;; vector 

{:name "Bear" :age 32} ;; map 

#{1 2 3} ;; set

其中 let 可以對 vector 和 map 進行 deconstruction。

let 對 vector 進行 deconstruction 的例子:

(def position-2d [3 4])

(defn dist-2d
  [position-2d]
  (let [[x y] position-2d
         x2 (* x x)
         y2 (* y y)]
    (Math/sqrt (+ x2 y2))))

(println (dist-2d position-2d))

deconstruction 時會忽略多於的參數:

(def position-3d [3 4 5])

(defn dist-2d
  [position-3d]
  (let [[x y] position-3d
         x2 (* x x)
         y2 (* y y)]
    (Math/sqrt (+ x2 y2))))

(println (dist-2d position-3d))

5. destructuring a map with let:

let 對 map 進行 deconstruction 的例子:

(def position-3d {:x 3 :y 4 :z 5})

(defn dist-2d
  [position-3d]
  (let [{x :x y :y} position-3d
         x2 (* x x)
         y2 (* y y)]
    (Math/sqrt (+ x2 y2))))

(println (dist-2d position-3d))

透過 :keys 可以將對應的 key 取出:

(def position-3d {:x 3 :y 4 :z 5})

(defn dist-2d
  [position-3d]
  (let [{:keys [x y]} position-3d
         x2 (* x x)
         y2 (* y y)]
    (Math/sqrt (+ x2 y2))))

(println (dist-2d position-3d))

留言

熱門文章