3

I believe Emacs lists have nil at their end. That said, I was trying to test examples.
Can anyone tell the difference between a and b?

(setq a '(foo))  
(setq b '(foo nil))  

;; Returns nil and (nil), respectively.
(cdr a)
(cdr b)
4
  • 2
    a is (foo . nil). b is (foo . (nil . nil)).
    – Toothrot
    Apr 15 '20 at 18:39
  • 2
    And (cdr nil) and (car nil) return nil (by convention, for convenience).
    – Drew
    Apr 15 '20 at 20:02
  • @Toothrot or OP: Please consider posting that as an answer.
    – Drew
    Apr 15 '20 at 20:03
  • 2
    a is a list with one element: foo. b is a list with two elements: foo and nil.
    – Drew
    Apr 15 '20 at 20:04
4

It is in a sense true that a proper list ends in nil, but not in the sense that the last element of every proper list is nil. It is the cdr of the innermost cons of the proper list that is nil. A cons is a car-cdr pair. A proper list is a nest of conses, or rather, a proper list is either nil or a cons whose cdr is a proper list. So a finite proper list is a nest of conses whose innermost cons's cdr is nil. Its elements are its cars. The proper list (a b c) is a cons whose car is a and whose cdr is (b c), whose cdr is (c), whose cdr is nil. The last element is c, not nil; but the last (or innermost) cdr is indeed nil; this is what ends a proper list.

In dotted-pair notation, which shows the cons structure of a list, (a b c) is (a . (b . (c . nil))).

A list simpliciter is either nil or a cons whose cdr is not necessarily a list.

Your a is (foo . nil) and your b is (foo . (nil . nil)).

And (cdr b) is (nil) because (nil . nil) is (nil), the list whose only element is nil.

For more on conses, evaluate (info "(elisp) Cons Cell Type").

3
  • I think it would be useful to link to (info "(elisp) Cons Cell Type") and subnodes.
    – Basil
    Apr 15 '20 at 22:34
  • @phils, Graham calls it dot notation.
    – Toothrot
    Apr 16 '20 at 0:03
  • @Toothrot Fair enough -- please change it back if you prefer. It's always "dotted pair notation" in the elisp manual, which is why I edited that, but I think it's good either way.
    – phils
    Apr 16 '20 at 0:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.