7

I am new to Lisp so this might be so simple but I am curious to know about this in any case.

I am familiar with logical operators like AND and OR but lisp does not seem to behave as expected.

For example, For (and 1 8)

Expected:

1 => 0 0 0 1
8 => 1 0 0 0
(and 1 8) => 0 0 0 0

Received: So, the answer should have been 0 ...but instead it is 8

Questions:

  1. How is this calculation done in LISP?
  2. Is Logical operators fundamentally different in LISP?
3
  • 1
    In Lisp, NIL is the only falsey value, everything else is truthy. Commented Apr 12, 2017 at 20:16
  • 1
    (logand 1 8) is 0 Commented Apr 12, 2017 at 20:17
  • 1
    What languages are you comparing with? 1 and 8 is 8 in Python, too, and 1 && 8 is an error in Java. In C++, 1 && 8 is true. In Ruby, 1 and 8 is 1. In JavaScript, 1 && 8 is 8. Commented Apr 13, 2017 at 10:04

2 Answers 2

10

In Common Lisp, AND and OR operate on boolean values, not binary digits. NIL is the only false value, anything else is considered true.

To operate on the binary representation of numbers, use LOGAND, LOGIOR, etc. These are all documented at http://clhs.lisp.se/Body/f_logand.htm.

(logand 1 8) ==> 0
Sign up to request clarification or add additional context in comments.

Comments

6

In programming languages there are often two types of and and or operator. The Conditional Operators are called && and || in Algol languages and in Common Lisp they are called and and or. On the other hand the arithmetic operators &, and | have CL equivalents logand and logior.

In Common Lisp every value are booleans and with the exception of nil every other value is considered a true value. Perl is very similar except it has a couple of false values, however 1 and 8 are true values in both languages:

1 && 8 # ==> 8
1 & 8  # ==> 0
1 || 8 # ==> 1
1 | 8  # ==> 9

Same in CL

(and 1 8)    ; ==> 8
(logand 1 8) ; ==> 0
(or 1 8)     ; ==> 1
(logior 1 8) ; ==> 9

1 Comment

Note that Perl uses # for comments, not //.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.