Lisp——case 結構



case 結構像 cond 結構那樣實施多個測試-動作子句。但是,它會評估一個鍵形式,並基於該鍵形式的評估允許多個動作子句。

case 宏的語法如下 −

CASE 的模板如下:

(case  (keyform)
((key1)   (action1   action2 ...) )
((key2)   (action1   action2 ...) )
...
((keyn)   (action1   action2 ...) ))

示例

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

main.lisp

; set day as 4
(setq day 4)
; compare day with corresponding cases and print the respective day
(case day
   (1 (format t "~% Monday"))
   (2 (format t "~% Tuesday"))
   (3 (format t "~% Wednesday"))
   (4 (format t "~% Thursday"))
   (5 (format t "~% Friday"))
   (6 (format t "~% Saturday"))
   (7 (format t "~% Sunday")))

輸出

單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果 −

Thursday

示例

更新名為 main.lisp 的原始碼檔案並輸入以下程式碼。在此示例中,我們將基於用例執行不同的操作。

main.lisp

; set a as 2
(setq a 2)
; set b as 3
(setq b 3)
; set c as 3 to represent a case for multiplication
(setq c 3)

; compare c with corresponding cases and print the respective operation result
(case c
   (1 (print (+ a b)))  ; get sum
   (2 (print (- a b)))  ; get substraction
   (3 (print (* a b)))  ; get multiplication 
   (4 (print (/ a b))))  ; get division

輸出

單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果 −

6
lisp_decisions.htm
廣告
© . All rights reserved.