7

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.

Ben
  • 51,770
  • 36
  • 127
  • 149
Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132

4 Answers4

11

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. CARs and CDRs 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.

Pillsy
  • 9,781
  • 1
  • 43
  • 70
9

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.

Chris Johnsen
  • 214,407
  • 26
  • 209
  • 186
3

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.

Iceland_jack
  • 6,848
  • 7
  • 37
  • 46
-1

When you iterate over a list you know you reached the end when you hit nil. What you have is a list with a car and a point pair.

thelost
  • 6,638
  • 4
  • 28
  • 44