Lisp-logical-operators

提供:Dev Guides
移動先:案内検索

LISP-論理演算子

Common LISPは、ブール値を操作する* and、or、、 *not の3つの論理演算子を提供します。 A の値がnilで、 B の値が5であると仮定します-

Operator Description Example
and It takes any number of arguments. The arguments are evaluated left to right. If all arguments evaluate to non-nil, then the value of the last argument is returned. Otherwise nil is returned. (and A B) will return NIL.
or It takes any number of arguments. The arguments are evaluated left to right until one evaluates to non-nil, in such case the argument value is returned, otherwise it returns nil. (or A B) will return 5.
not It takes one argument and returns t *if the argument evaluates to nil.* (not A) will return 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

論理演算はブール値で機能し、2番目に、数値ゼロとNILは同じではないことに注意してください。