Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List without nil in Lisp

Tags:

list

null

lisp

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.

like image 410
Stan Kurilin Avatar asked Mar 04 '10 16:03

Stan Kurilin


3 Answers

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.

like image 118
Pillsy Avatar answered Oct 10 '22 08:10

Pillsy


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.

like image 9
Chris Johnsen Avatar answered Oct 10 '22 08:10

Chris Johnsen


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.

like image 3
Iceland_jack Avatar answered Oct 10 '22 07:10

Iceland_jack