LISP - 逻辑运算符


Common LISP 提供了三种逻辑运算符:and、ornot,它们对布尔值进行运算。假设A的值为 nil,B的值为 5,则 -

操作员 描述 例子
它需要任意数量的参数。参数从左到右计算。如果所有参数的计算结果均为非零,则返回最后一个参数的值。否则返回 nil。 (和 AB)将返回 NIL。
或者 它需要任意数量的参数。参数从左到右计算,直到计算结果为非 nil,在这种情况下返回参数值,否则返回nil (或 AB)将返回 5。
不是 它接受一个参数,如果该参数的计算结果为nil ,则返回t (不是 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 不同。

lisp_operators.htm