Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lisp - How can I check if a list is a dotted pair?

How can I check if a list in lisp is a dotted pair?

CL-USER 20 : 3 > (dotted-pair-p (cons 1 2))
T

CL-USER 20 : 3 > (dotted-pair-p '(1 2))
NIL

CL-USER 20 : 3 > (dotted-pair-p '(1 2 3))
NIL

I tried checking if length=2 but got error:

CL-USER 28 : 1 > (= (length (cons 2 3)) 2)
Error: In a call to LENGTH of (2 . 3), tail 3 is not a LIST.
like image 233
זאבי כהן Avatar asked Jun 17 '12 14:06

זאבי כהן


2 Answers

A lisp list in "dotted pair notation" looks something like:

(1 . ()).

Since this is homework, I'll let you take this to the logical conclusion. Compare

(LIST 1 2) => (1 . (2 . ()))

with

(CONS 1 2) => (1 . 2).

What is different between these two? How can you tell the difference using predicates?

Remember all proper lisp lists end with the empty list. Ask yourself how do you access the second element of a cons pair? The solution from there ought to be clear.

like image 153
nixeagle Avatar answered Nov 15 '22 07:11

nixeagle


Because a list always ends with the empty list, while a pair doesn't:

(listp (cdr '(1 2))) => T
(listp (cdr '(1 . 2))) => NIL
like image 39
Diogo Franco Avatar answered Nov 15 '22 08:11

Diogo Franco