I know that in Lisp a list must end with nil, but expression like
(print (cons 1 (cons 3 2)))
does not throw any errors. It prints:
(1 3 . 2)
Is it correct?
I'm using GNU Clisp.
In Lisp, a proper list ends with NIL
, but you also have improper lists. One kind of improper list is a list where the last cons cell has an atom other than NIL
in its CDR
. (1 3 . 2)
is exactly such an improper list.
You can even have improper lists where it doesn't have a last cell at all. CAR
s and CDR
s are basically just pointers, so you can have circular lists!
In Common Lisp (which is the language CLISP implements), many standard functions won't work with improper lists as arguments.
What you have is a dotted list, which is a kind of improper list.
A chain of CONS cells where the last CDR is NIL is a proper list.
It's also interesting to note what happens when evaluating proper lists:
;; A proper list
(cons '+ (cons 5 (cons 10 '())))
⇒ (+ 5 10)
(eval (+ 5 10))
⇒ 15
versus evaluating dotted lists:
;; A dotted list
(cons '+ (cons 5 (cons 10 5000)))
⇒ (+ 5 10 . 5000)
(eval (+ 5 10 . 5000))
⇒ 15
It ignores the terminating atom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With