LISP - Operatori logici

Common LISP fornisce tre operatori logici: and, or, e notche opera su valori booleani. AssumereA ha valore nullo e B ha valore 5, quindi -

Operatore Descrizione Esempio
e Richiede un numero qualsiasi di argomenti. Gli argomenti vengono valutati da sinistra a destra. Se tutti gli argomenti restituiscono un valore diverso da zero, viene restituito il valore dell'ultimo argomento. Altrimenti viene restituito zero. (e AB) restituirà NIL.
o Richiede un numero qualsiasi di argomenti. Gli argomenti vengono valutati da sinistra a destra finché non si valuta un valore diverso da zero, in tal caso viene restituito il valore dell'argomento, altrimenti viene restituitonil. (o AB) restituirà 5.
non Richiede un argomento e restituisce t se l'argomento restituisce nil. (non A) restituirà T.

Esempio

Crea un nuovo file di codice sorgente denominato main.lisp e digita il codice seguente.

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

Quando fai clic sul pulsante Esegui o digiti Ctrl + E, LISP lo esegue immediatamente e il risultato restituito è -

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

Si noti che le operazioni logiche funzionano su valori booleani e in secondo luogo, numeric zero and NIL are not same.