- LISP 教程
- LISP - 首頁
- LISP - 概述
- LISP - 環境
- LISP - 程式結構
- LISP - 基本語法
- LISP - 資料型別
- LISP - 宏
- LISP - 變數
- LISP - 常量
- LISP - 運算子
- LISP - 決策
- LISP - 迴圈
- LISP - 函式
- LISP - 謂詞
- LISP - 數字
- LISP - 字元
- LISP - 陣列
- LISP - 字串
- LISP - 序列
- LISP - 列表
- LISP - 符號
- LISP - 向量
- LISP - 集合
- LISP - 樹
- LISP - 雜湊表
- LISP - 輸入與輸出
- LISP - 檔案I/O
- LISP - 結構體
- LISP - 包
- LISP - 錯誤處理
- LISP - CLOS
- LISP 有用資源
- Lisp - 快速指南
- Lisp - 有用資源
- Lisp - 討論
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
廣告