ANDing a boolean and a list
Asked Answered
E

3

6

I've noticed in Scheme, Racket, and Clojure that the expression (using Clojure here) (and true '()) evaluates to (), and (and '() true) evaluates to true. This is true not only for the empty list, but for any list.

But in GNU CLISP and Emacs Lisp, (and t '()) evaluates to nil and (and '() t) evaluates to nil also, but (and t '(1 2 3)) evaluates to (1 2 3) and (and '(1 2 3) t) evaluates to t.

What is going on here?

Eccentricity answered 17/11, 2016 at 17:8 Comment(0)
P
9

In the first group of languages, the empty list is not treated as 'falsey' and is instead treated as a 'truthy' value. In scheme and racket, #false is the only false value so even though '() is null, null is not false; in clojure the empty list is not the same as nil, so it is 'truthy' there as well.

In the second group, the empty list is a synonym for nil and is treated as false, leading the condition to return nil. A list with elements however is not the same as nil, and thus is treated as a truthy value again.

The final piece of the puzzle is that and returns the last truthy value if all values passed are truthy.

Pouter answered 17/11, 2016 at 17:12 Comment(4)
But in Scheme and Racket, (null? '()) is true. In Clojure, (nil? '()) is indeed false.Eccentricity
@clementi In Scheme and Racket, null is the same value as '(), but it (1) is truthy and (2) prints as () or '(). In CL and elisp, nil is the same value as '(), but (1) it’s falsy, and (2) it prints as nil, not ().Emogeneemollient
@clementi updated my answer; alexis is exactly right.Pouter
null and nil are very different. In Racket null means empty list, and that's all it means; it's not a boolean, so it is a 'truthy' value. In Clojure nil does not mean empty list; it's closer to a void value, so the empty list is 'truthy' there as well. Many lisps outside of those get nil very confused (in my opinon), making it a list, and a boolean, and a symbol, all at the same time.Divulgate
E
2

In Clojure only false and nil are regarded as logically false. Everything else is regarded as logically true.

In the other Lisps you mention, the empty list is regarded as logically false.

Elixir answered 17/11, 2016 at 17:11 Comment(0)
C
2

The and operator evaluates the arguments and 'shortcircuits' the result, i.e. as soon as one argument is false, it returns nil. Otherwise, it returns the last value. The difference in behavior is that in Common Lisp, the empty list is the same thing as nil, which is the same as false, therefore, (and '() t) is the same as (and nil t) which returns nil.

Coronet answered 17/11, 2016 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.