📜  LISP 中的案例构造

📅  最后修改于: 2022-05-13 01:54:46.906000             🧑  作者: Mango

LISP 中的案例构造

在本文中,我们将讨论 LISP 中的case 构造。这用于一次检查多个测试条件,与 cond 不同,如果和何时允许多个条件。

句法:

(case  (key_value)
((key1)   (statement 1 .............. statement n) )
((key2)   (statement 1 .............. statement n) )
................
((keyn)   (statement 1 .............. statement n) )

这里,

  • key_value是输入的数值
  • 是测试键中指定的特定条件的不同条件

示例 1: LISP 程序在给定数字时获取特定数字。

Lisp
;define value to 2
(setq val1 2)
 
;define 5 cases from 1 to 5
(case val1
(1 (format t "you selected number 1"))
(2 (format t "you selected number 2"))
(3 (format t "you selected number 3"))
(4 (format t "you selected number 4"))
(5 (format t "you selected number 5"))
)


Lisp
;define value1 to 10
(setq val1 10)
 
;define value2 to 20
(setq val2 20)
 
;set input to 1
(setq input 1)
 
;define 4 cases to perform each arithmetic operation
(case input
 
;condition to perform addition
(1 (print (+ val1 val2)))
 
;condition to perform subtraction
(2 (print (- val1 val2)))
 
;condition to perform multiplication
(3 (print (* val1 val2)))
 
;condition to perform division
(4 (print (/ val1 val2)))
)


Lisp
;define value1 to 10
(setq val1 10)
 
;define value2 to 20
(setq val2 20)
 
;set input to 3
(setq input 3)
 
;define 4 cases to perform each arithmetic operation
(case input
 
;condition to perform addition
(1 (print (+ val1 val2)))
 
;condition to perform subtraction
(2 (print (- val1 val2)))
 
;condition to perform multiplication
(3 (print (* val1 val2)))
 
;condition to perform division
(4 (print (/ val1 val2)))
)


输出

you selected number 2

示例 2:选择特定键时执行算术运算的 LISP 程序。

语言

;define value1 to 10
(setq val1 10)
 
;define value2 to 20
(setq val2 20)
 
;set input to 1
(setq input 1)
 
;define 4 cases to perform each arithmetic operation
(case input
 
;condition to perform addition
(1 (print (+ val1 val2)))
 
;condition to perform subtraction
(2 (print (- val1 val2)))
 
;condition to perform multiplication
(3 (print (* val1 val2)))
 
;condition to perform division
(4 (print (/ val1 val2)))
)

输出

30 

现在,如果我们将输入设置为 3:

语言

;define value1 to 10
(setq val1 10)
 
;define value2 to 20
(setq val2 20)
 
;set input to 3
(setq input 3)
 
;define 4 cases to perform each arithmetic operation
(case input
 
;condition to perform addition
(1 (print (+ val1 val2)))
 
;condition to perform subtraction
(2 (print (- val1 val2)))
 
;condition to perform multiplication
(3 (print (* val1 val2)))
 
;condition to perform division
(4 (print (/ val1 val2)))
)

输出

200