I am learning LISP using PC Scheme TI implementation and from the book ‘Structure and Interpretation of Computer Programs’. PC scheme doesn’t seem to have a ‘nil’ variable
[VM ERROR encountered!] Variable not defined in current environment
NIL
Instead ‘()’ seems to work.
[55] (define one-through-four (list 1 2 3 4 ()))
ONE-THROUGH-FOUR
Do both have the same meaning? What is the correct way to use a sequence of no elements in the PC scheme dialect?
Thanks.
When you say that this dialect “does not have a NIL variable”, you are right in two ways. Not only does not
nilexist, but it seems to be treated as an ordinary symbol that you can use as a variable. It says “Variable not defined”.In Lisp dialects where
nilhas a special meaning,nilusually cannot be used as a variable.nilis equivalent to()only in “classical” Lisps (my term). By this I mean Lisps that are related by ancestry or imitation to the original John MacCarthy Lisp. Emacs Lisp and Common Lisp are that way. The classical Lisps usenilas the list terminator: i.e.(cons 1 nil)producing the list(1)Scheme is not a classical Lisp in this sense. There is no
nil. It uses()as the printed notation for an empty list and when you want that value in an expression, it is quoted, just like a non-empty list literal:'(). In Scheme,(cons 1 nil)is written(cons 1 '()). Boolean false is represented by an object which is notated#f. An empty list is true not false, so(if '() 1 2)yields 1, not 2 like in a classical Lisp. Neither'()nor#fare symbols.Scheme is also case-sensitive. Even if you do have a variable
NILin Scheme, it has nothing to do withnil. You can use both as variable names.The SICP text causes confusion on this topic by, in its early chapters, making references to a variable called
nilwhich holds the value of'(). There is no such variable in Scheme; you have to make it yourself if you want those examples to work. This is an unfortunate aspect of the textbook.If you define a variable
nilwhose value is the object'(), so that that Chapter 2 code from SICP works, it is still not equivalent to an empty list the way it is in a classical Lisp, because in a classical Lisp,niland()are equivalent notations for a symbol. The symbolnilitself is the empty list, and vice versa. It is not the name of a variable which merely holds a list. And so the quote expression'nilalso evaluates to the empty list! Whereas in scheme'nilevaluates to the ordinary symbolnileven if you’ve defined it as a variable holding the empty list.Regarding the second question, “() seems to work, do both have the same meaning?”. The “same meaning” aspect is covered above: no, not the same meaning in Scheme. As far as it working, consider the following quote from the R5RS Scheme Report:
Therefore this loose treatment of
()as valid expression that produces the empty list appears to be a PC Scheme extension of behavior, not standard Scheme. It is accepting an expression which is not a syntactically valid Scheme expression.