Lisp - How to check if a list is a dotted pair?

How to 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 to check if length=2 , but got an 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. 
+4
source share
4 answers

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

 (1 . ()). 

Since this is homework, I will let you bring it to its logical conclusion. Compare

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

from

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

How are these two different? How can you spot the difference using predicates?

Remember that all matching lisp lists end with an empty list. Ask yourself, how do you access the second element of the cons pair? The solution from there should be clear.

+9
source

Since the list always ends with an empty list, and the pair does not matter:

 (listp (cdr '(1 2))) => T (listp (cdr '(1 . 2))) => NIL 
+2
source
 (not(listp(cdr (cons 1 2))))=> T (not(listp(cdr (list 1 2))))=> nill 
0
source

You can check if the list is dotted (ends with a non-nil atom):

 (defun dotted-listp (l) (cond ((null l) nil) ((atom l) t) (t (dotted-listp (cdr l))))) 
0
source

All Articles