Lisp - Cond 結構



LISP 中的cond結構最常用於實現分支。

cond的語法為:

(cond   (test1    action1)
   (test2    action2)
   ...
   (testn   actionn))

cond語句中的每個子句都包含一個條件測試和一個要執行的動作。

如果cond之後第一個測試test1評估結果為真,則執行相關的動作部分action1,返回其值,並跳過其餘子句。

如果test1評估結果為nil,則控制流移動到第二個子句,而無需執行action1,並遵循相同的過程。

如果所有測試條件的評估結果均為假,則cond語句返回nil。

示例

建立名為main.lisp的原始碼檔案,並在其中鍵入以下程式碼。這裡我們使用帶有失敗條件的cond結構。

main.lisp

; set a as 10
(setq a 10)
; check a being greater than 20
(cond ((> a 20)
   (format t "~% a is greater than 20"))  ; statement is not printed as case is not true
   (t (format t "~% value of a is ~d " a))) ; otherwise print the statement

單擊“執行”按鈕或鍵入Ctrl+E時,LISP會立即執行它,返回的結果為:

value of a is 10

請注意,第二個子句中的t確保如果其他子句都不滿足,則執行最後一個動作。

示例

更新名為main.lisp的原始碼檔案,並在其中鍵入以下程式碼。這裡我們使用帶有成功條件的cond結構。

main.lisp

; set a as 30
(setq a 30)
; check a being greater than 20
(cond ((> a 20)
   (format t "~% a is greater than 20")) ;  statement is printed as case is true
   (t (format t "~% value of a is ~d " a))) ; statement is not printed

單擊“執行”按鈕或鍵入Ctrl+E時,LISP會立即執行它,返回的結果為:

a is greater than 20

示例

更新名為main.lisp的原始碼檔案,並在其中鍵入以下程式碼。這裡我們使用帶有否定條件的cond結構。

main.lisp

; set a as 30
(setq a 30)
; check not a as false
(cond ((not a)
   (format t "~% a " a)) ; statement is not printed
   (t (format t "~% NOT a is Nil ~d" a))) ; 

單擊“執行”按鈕或鍵入Ctrl+E時,LISP會立即執行它,返回的結果為:

NOT a is Nil 30
lisp_decisions.htm
廣告
© . All rights reserved.