A cons in Lisp is any Lisp object whose references point to a cons cell in memory.
Any list other than NIL is a cons.
Any dotted pair is a cons.
A dotted pair, e.g., (A . B), is represented by a single Cons cell in memory.
Every nonempty list can be represented by an expression using dotted pairs and no space-separated list elements.
( ) is equivalent to
NIL
(A) is equivalent to (A .
NIL)
(A B) is equivalent
to (A . (B . NIL))
(A B C) is equivalent to (A . (B
. (C . NIL)))
The Lisp reader accepts both list notation and dotted pair notation.
The Lisp printer always tries to express its output with list notation insofar as possible. Some conses cannot be fully converted to list notation.
For example, ((A . B) . C)
must be printed in dotted-pair notation.
;;; COUNTATOMS
;;; Return the number of atoms
in LST.
;;;
(defun countatoms (lst)
(cond ((atom lst)
1)
(t (+ (countatoms (car lst))
(countatoms (cdr lst)) )) ) )
> (setq f
#'+)
#<function ...>
APPLY causes a functional argument to be applied to a list of arguments.
> (apply f
'(1 2 3 4 5))
15
> (defun sqr (x) (*
x x))
SQR
> (apply #'sqr '(7))
49
> (defun sqr-list (lst)
(if (null lst) nil
(cons (sqr (car lst))
(sqr-list (cdr lst)) ) ) )
Recursion with APPLY:
> (defun apply-to-list
(fn lst)
(if (null lst) nil
(cons (apply fn (list (car lst)))
(apply-to-list fn (cdr lst)) ) ) )
> (apply-to-list #'sqr
'(1 2 3 4 5))
(1 4 9 16 25)
MAPCAR does it for you...
> (mapcar #'sqr
'(1 2 3 4 5))
(1 4 9 16 25)
> (print-all-sublists '(a
(b c) d (e (f))) )
(A (B C) D (E (F)))
(B C)
(E (F))
(F)
> (defun print-all-sublists
(lst)
(if (listp lst)
(progn
(print lst)
(dolist (sublist lst)
(print-all-sublists sublist) ) ) ) )
Last modified: October 5, 1998
Steve Tanimoto