A dotted pair is a cons cell where it's CDR is not a cons itself (recursive definition). So this '(1 . 2)
is a dotted pair, but this '(1 . ())
isn't, since it is just the printed representation of and the same as '(1)
.
(defun dotted-pair-p (x)
(and (consp x)
;; Check that CDR is not a list with LISTP
;; since (CONSP ()) ;;=> NIL
;; and the CDR of a pair can't be NIL for it
;; to be dotted.
(not (listp (cdr x)))))
(dotted-pair-p '(1 . 2)) ;T
(dotted-pair-p '(1 . ())) ;NIL
Dotted lists (lists whose last cons cell is dotted) are defined in Common Lisp by LIST*
. We can now use the above function to define a predicate for them too:
(defun list*p (x)
(dotted-pair-p (last x)))
(list*p (list* 1 2 3 4)) ;T
(list*p (list 1 2 3 4)) ;NIL
length
is going to assume there is an empty list. That is how it knows to stop. – Summerlin(= (length (cons 2 3) 2))
should be(= (length (cons 2 3)) 2)
. – Weinshienk