DAY 11
0
Software Development

# 流程控制（一）

## 條件式

### if, if-not

``````(if 42 "answer")
;; => nil
(if "hi" "say hi" "say no")
;; => "say hi"
(if true "it's true" "it's false")
;; => "it's true"
(if false "it's true" "it's false")
;; => "it's false"
``````

``````(if true
(do
(println "Success")
"It's true")
(do
(println "Fail")
"It's false"))
;; => Success
;; => "It's true"
``````

`if-not``if` 的反面，如果 `if-not` 的條件測試爲真，則會對第三個參數運算式求值，否則會對第二個參數求值：

``````(if-not true "it's true" "it's false")
;; => "it's false"
(if-not false "it's true" "it's false")
;; => "it's true"
``````

### when, when-not

`when` 是少了 else 部分的 `if` 運算式，`when` 接受一個測試函式，如果測試函式返回真，則會對 `when` 的本體運算式求值後返回其值，反之則回傳 `nil`

``````(when false "nothing")
;; => nil
(when true "anything")
=> "anything"
``````

`when-not` 就是 `when` 的反面，如果接收的測試函式返回假，便對本體運算式求值後返回其值，反之則回傳 `nil`

``````(when-not (> 5 2) "Five")
;; => nil
(when-not (> 2 5) "Two")
;; => "Two"
``````

### if-let, when-let

``````(let [is-small (< 5 100)]
(if is-small
"smaller"
"bigger"))
;; => "smaller"
``````

Clojure 提供了簡便的寫法將兩者整合在一起，有 `if-let``when-let` 兩個版本可用：

``````(if-let [is-smaller (< 5 100)]
"smaller"
"greater")
;; => "smaller"
(when-let [is-greater (> 100 5)]
"greater")
;; => "greater"
``````

### cond

`cond` 運算式類似於其他語言中的 `switch-case``if-elsif`，它接受一對對運算式，每對運算式都有條件式，以及當條件式成立時，待求值的運算式。它會根據每對運算式，照順序對各個條件式一一測試，只要有一條件式爲真，則求值對應的運算式，就不會再往下求值：

``````(let [x 1]
(cond
(> x 0) "greater"
(= x 0) "zero"
(< x 0) "smaller"))
;; => "greater"
``````

``````(let [temperature 20]
(cond
(> temperature 30) "Hot"
(< temperature 15) "Cold"
:default "Normal"))
;; => "Normal"
``````

### case

`case``cond` 非常類似，`case` 會以第一個參數，與之後成對的運算式中的第一個運算式相比較，若相等則回傳之後的運算式求值的結果；若沒有任何一個相等，將丟出 IllegalArgumentException 例外：

``````(let [color "red"]
(case color
"red" "Rose"
"white" "Paper"
"Blue" "Sky"))
;; => "Rose"

(let [capital "Canberra"]
(case capital
"Dublin" "Ireland"
"Cairo" "Egypt"
"Tokyo" "Japan"))
;; => IllegalArgumentException No matching clause: Canberra
``````

（未完待續）