3 ms·
What useful idiom is afforded by nil being a symbol?
by bhk 4y ago
What useful idiom is afforded by nil being a symbol?
- kazinator 4y agoThere are a number of benefits. One is that, in the role of the list terminator, nil effectively serves as a symbol. It is unique, and tested for its identity: if the cdr of the cell of a list is the nil object, then that is the last cell. This is how symbols are used. Anything that is exploited for its unique identity should be a symbol. Nil isn't necessarily implemented the same way as other symbols. It could actually be a null pointer. One way to look at it is that something now known as the GoF Null Object Pattern is at work. All the functions which take a symbolic argument, such as symbol-name, symbol-value, symbol-package, ... are made to work with a nil argument. Just like (car nil) is made work with a nil argument, even though nil isn't a cons. Being able to pass nil to symbol functions makes some things work that otherwise wouldn't, which can reduce the code. All the special case testing (if necessary) is done in the library already. Say we have a hash table H which maps keys to symbols. We can do, say, (symbol-value (gethash K H)). If K is not found in the table, gethash will return nil. Because nil is a symbol, (symbol-value nil) works fine and returns nil. If that's what we want in the not found case, it keeps our code short and sweet. Whenever some slot or variable defaults to nil, it's not only defaulting to a false value, and empty list, but to a valid symbol object that can be passed to symbol API's. If the empty list weren't a symbol, it could be notated (), and nothing but that. That notation works grewat when we are dealing with the empty list semantics. It's not so nice when () is denoting false, other than () kind of looking like a zero. When () denotes the bottom type in the type system, things are also not nice; all other types are either symbols or expressions like (or integer string). It's much nicer to have a word like "nil" for all these roles.