條件構造
在 Common Lisp 中,if 是最簡單的條件構造。它具有 (if test then [else]) 的形式,如果 test 為真,則評估為 then,否則評估為 else。else 部分可以省略。
(if (> 3 2)
"Three is bigger!"
"Two is bigger!")
;;=> "Three is bigger!"
Common Lisp 中的 if 和許多其他程式語言中的 if 之間的一個非常重要的區別是 CL 的 if 是一個表示式,而不是一個語句。因此,if 形成返回值,可以將其分配給變數,在引數列表中使用等:
;; Use a different format string depending on the type of x
(format t (if (numberp x)
"~x~%"
"~a~%")
x)
Common Lisp 的 if 可以被認為等同於三元運算子?: 在 C#和其他大括號語言中。
例如,以下 C#表示式:
year == 1990 ? "Hammertime" : "Not Hammertime"
等效於以下 Common Lisp 程式碼,假設 year 包含一個整數:
(if (eql year 1990) "Hammertime" "Not Hammertime")
cond 是另一個條件結構。它有點類似於 if 語句鏈,並具有以下形式:
(cond (test-1 consequent-1-1 consequent-2-1 ...)
(test-2)
(test-3 consequent-3-1 ...)
... )
更準確地說,cond 有零個或多個子句,每個子句有一個測試,後跟零個或多個結果。整個 cond 構造選擇第一個子句,其測試不評估為 nil 並按順序評估其結果。它返回結果中最後一個表單的值。
(cond ((> 3 4) "Three is bigger than four!")
((> 3 3) "Three is bigger than three!")
((> 3 2) "Three is bigger than two!")
((> 3 1) "Three is bigger than one!"))
;;=> "Three is bigger than two!"
要提供一個 default 子句來評估是否有其他子句的計算結果為 t,你可以使用 t 新增一個預設為 true 的子句。這在概念上與 SQL 的 CASE...ELSE 非常相似,但它使用文字布林值而不是關鍵字來完成任務。
(cond
((= n 1) "N equals 1")
(t "N doesn't equal 1")
)
if 構造可以寫成 cond 構造。(if test then else) 和 (cond (test then) (t else)) 是等價的。
如果你只需要一個子句,請使用 when 或 unless:
(when (> 3 4)
"Three is bigger than four.")
;;=> NIL
(when (< 2 5)
"Two is smaller than five.")
;;=> "Two is smaller than five."
(unless (> 3 4)
"Three is bigger than four.")
;;=> "Three is bigger than four."
(unless (< 2 5)
"Two is smaller than five.")
;;=> NIL