Lisp - 如果構造



if 宏後面接著一個對 t 或 nil 求值的測試子句。如果測試子句被求值為 t,則執行測試子句之後的動作。如果它為 nil,則求值下一個子句。

if 的語法 -

(if (test-clause) (action1) (action2))

示例

建立一個名為 main.lisp 的新原始碼檔案,並輸入以下程式碼。

main.lisp

; set a as 10
(setq a 10)

; check if a is greater than 20
(if (> a 20)
   ; print the result if a is less than 20
   (format t "~% a is less than 20"))
; print the value of a   
(format t "~% value of a is ~d " a)

輸出

當你點選執行按鈕,或按 Ctrl+E 時,LISP 會立即執行它,返回的結果是 -

value of a is 10

示例

if 子句後面可以跟一個可選的 then 子句。

建立一個名為 main.lisp 的新原始碼檔案,並輸入以下程式碼。

main.lisp

; set a as 10
(setq a 10)
; check if a is greater than 20
(if (> a 20)
   ; print statement if a is greater than 20
   then (format t "~% a is less than 20"))
; print value of a   
(format t "~% value of a is ~d " a)

輸出

當你點選執行按鈕,或按 Ctrl+E 時,LISP 會立即執行它,返回的結果是 -

a is less than 20
value of a is 10 

示例

你還可以使用 if 子句建立 if-then-else 型別的語句。

建立一個名為 main.lisp 的新原始碼檔案,並輸入以下程式碼。

main.lisp

; set a as 100
(setq a 100)
; if a is greater than 20
(if (> a 20)
   ; print statement if a is greater than 20
   (format t "~% a is greater than 20") 
   ; else print this statement
   (format t "~% a is less than 20"))
(format t "~% value of a is ~d " a)

輸出

當你點選執行按鈕,或按 Ctrl+E 時,LISP 會立即執行它,返回的結果是 -

a is greater than 20
value of a is 100  
lisp_decisions.htm
廣告
© . All rights reserved.