LISP - Opérateurs logiques

Common LISP fournit trois opérateurs logiques: and, or, et notqui fonctionne sur des valeurs booléennes. PrésumerA a une valeur nulle et B a la valeur 5, alors -

Opérateur La description Exemple
et Cela prend n'importe quel nombre d'arguments. Les arguments sont évalués de gauche à droite. Si tous les arguments ont une valeur non nulle, la valeur du dernier argument est renvoyée. Sinon, rien n'est retourné. (et AB) renverra NIL.
ou Cela prend n'importe quel nombre d'arguments. Les arguments sont évalués de gauche à droite jusqu'à ce que l'on évalue non nul, dans ce cas la valeur de l'argument est retournée, sinon elle retournenil. (ou AB) renverra 5.
ne pas Il prend un argument et retourne t si l'argument est évalué à nil. (pas A) retournera T.

Exemple

Créez un nouveau fichier de code source nommé main.lisp et tapez le code suivant dedans.

(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))

Lorsque vous cliquez sur le bouton Exécuter ou tapez Ctrl + E, LISP l'exécute immédiatement et le résultat renvoyé est -

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

Veuillez noter que les opérations logiques fonctionnent sur les valeurs booléennes et d'autre part, numeric zero and NIL are not same.