LISP - 逻辑运算符
Common LISP 提供了三种逻辑运算符:and、or、 和 not,它们对布尔值进行运算。 假设 A 的值为 nil,B 的值为 5,则 −
运算符 | 描述 | 示例 |
---|---|---|
and | 它需要任意数量的参数。 参数从左到右计算。 如果所有参数的计算结果均为非零,则返回最后一个参数的值。 否则返回 nil。 | (and A B)将返回 NIL。 |
or | 它需要任意数量的参数。 参数从左到右计算,直到计算结果为非零,在这种情况下返回参数值,否则返回nil。 | (or A B) 将返回 5。 |
not | 它接受一个参数,如果该参数的计算结果为nil,则返回t。 | (not A) 将返回 T。 |
示例
创建一个名为 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
请注意,逻辑运算适用于布尔值,其次,数字零和 NIL 不同。