Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the exact difference between NULL and NIL in Common Lisp?

As far as I understood, NIL is a symbol for many things: empty lists, or the boolean false. So far so good, but why there is sometimes NULL showing up in the output?

clisp> (type-of NIL)
NULL
clisp> (type-of t)
BOOLEAN
clisp> (type-of (not t))
NULL
clisp> NIL
NIL
clisp> (eq NULL NIL)
ERROR..

So NULL is not a defined symbol as "BASIC-STRING-6" is not one either. But I am a little confused by the term NULL as a boolean should stay a boolean nonetheless if it is negated or not.

like image 357
math Avatar asked Dec 01 '22 16:12

math


2 Answers

NIL is a symbol. It's also written as (). The output of type-of is not necessarily useful here. the HyperSpec says about type-of:

Returns a type specifier, typespec, for a type that has the object as an element.

But given type hierarchies, as well as a universal type (everything is of type t), the output of type-of can be unhelpful. What's more useful here, if you want to know whether something has a particular type is typep. Using typep, we can see that, regardless of what type-of tells us, that nil is a boolean, is a symbol, and is a list, and a null. On the other hand, t is a symbol, a boolean, not a list, and not a null.

CL-USER> (type-of nil)
NULL
CL-USER> (type-of t)
BOOLEAN
CL-USER> (typep nil 'boolean)   ; both are booleans
T
CL-USER> (typep t 'boolean)
T
CL-USER> (typep nil 'symbol)    ; both are symbols
T
CL-USER> (typep t 'symbol)
T
CL-USER> (typep nil 'list)      ; only nil is a list
T
CL-USER> (typep t 'list)
NIL
CL-USER> (typep nil 'null)      ; only nil is a null
T
CL-USER> (typep t 'null)
NIL
like image 187
Joshua Taylor Avatar answered Dec 19 '22 03:12

Joshua Taylor


You might think it's strange that T is a boolean while NIL isn't. The reason is that NIL has several hats. It's the empty list, it's the symbol NIL, it's boolean false. So it sometimes occurs in contexts not appropriate for a boolean-typed value, hence the type boolean is not appropriate for it from a type-safety perspective. Somewhat similarly, in Scheme boolean false is different from the empty list.

NULL is given as the type of NIL.

NIL is the symbol that represents NULL in Common Lisp. It is also the representation of the empty list (). #'NULL is the function that checks if a variable is NULL (ie. eq NIL).

You may define NULL if you want to use NULL instead of NIL. (This is probably a terrible idea in practice.)

(defconstant null nil)
(type-of NULL) ; ==> NULL
NULL           ; ==> NIL
(eq NULL NIL)  ; ==> T
like image 37
Sylwester Avatar answered Dec 19 '22 04:12

Sylwester