Show 例子 3
优质
小牛编辑
136浏览
2023-12-01
通用LISP提供三个逻辑运算符: and, or,而not对布尔值进行操作。 假设A值为nil, B值为5,则 -
操作者 | 描述 | 例 |
---|---|---|
and | 它需要任意数量的参数。 参数从左到右进行评估。 如果所有参数都计算为非nil,则返回最后一个参数的值。 否则返回nil。 | (和AB)将返回NIL。 |
or | 它需要任意数量的参数。 从左到右计算参数,直到一个求值为非nil,在这种情况下返回参数值,否则返回nil 。 | (或AB)将返回5。 |
not | 它接受一个参数,如果参数的计算结果为nil. ,则返回t nil. | (不是A)将返回T. |
例子 (Example)
创建一个名为main.lisp的新源代码文件,并在其中键入以下代码。
(setq a 10)
(setq b 20)
(format t "~% A and B is ~a" (and a b))
(format t "~% A or B is ~a" (or a b))
(format t "~% not A is ~a" (not a))
(terpri)
(setq a nil)
(setq b 5)
(format t "~% A and B is ~a" (and a b))
(format t "~% A or B is ~a" (or a b))
(format t "~% not A is ~a" (not a))
(terpri)
(setq a nil)
(setq b 0)
(format t "~% A and B is ~a" (and a b))
(format t "~% A or B is ~a" (or a b))
(format t "~% not A is ~a" (not a))
(terpri)
(setq a 10)
(setq b 0)
(setq c 30)
(setq d 40)
(format t "~% Result of and operation on 10, 0, 30, 40 is ~a" (and a b c d))
(format t "~% Result of and operation on 10, 0, 30, 40 is ~a" (or a b c d))
(terpri)
(setq a 10)
(setq b 20)
(setq c nil)
(setq d 40)
(format t "~% Result of and operation on 10, 20, nil, 40 is ~a" (and a b c d))
(format t "~% Result of and operation on 10, 20, nil, 40 is ~a" (or a b c d))
单击“执行”按钮或键入Ctrl + E时,LISP立即执行它,返回的结果为 -
A and B is 20
A or B is 10
not A is NIL
A and B is NIL
A or B is 5
not A is T
A and B is NIL
A or B is 0
not A is T
Result of and operation on 10, 0, 30, 40 is 40
Result of and operation on 10, 0, 30, 40 is 10
Result of and operation on 10, 20, nil, 40 is NIL
Result of and operation on 10, 20, nil, 40 is 10
请注意,逻辑运算适用于布尔值,其次, numeric zero and NIL are not same.