Re: cons and list behaviour



Pascal Bourguignon wrote:
"Jason" <jemeade@xxxxxxxxx> writes:

Please excuse me if this has been addressed before. I searched the
recent posts and the FAQ and did not see find the answer I am seeking.

I am learnin LISP (actually elisp ;)), and have written the following:

;; here I am using cons notation
(setq node-1 (cons 'a 'b))
(setq node-2 (cons 'c 'd))
(setq node-3 (cons 'e node-1))
(setq node-4 (cons node-3 'f))
(setq node-5 (cons node-2 'g))
(setq tree (cons node-4 node-5))
;; (((e a . b) . f) (c . d) . g) <<<<< value

;; here we can see that a cons is *not* the same as a list
(setq tree2 (copy-tree tree)) ;; <<<<<<<<<<<< works fine
(setq tree3 (copy-sequence tree)) ;; <<<<<<<< generates an error!

;; now I am redefing the above using list notation
(setq node-1 (list 'a 'b))
(setq node-2 (list 'c 'd))
(setq node-3 (list 'e node-1))
(setq node-4 (list node-3 'f))
(setq node-5 (list node-2 'g))
(setq tree (list node-4 node-5))
;; (((e (a b)) f) ((c d) g)) <<<<< value

;; however, here we see that a list *is* the same as a cons!

This is not entirely true either:

(consp '()) --> nil

A list is either a cons, or the symbol nil, which can also be printed as: ()

A proper-list is either a cons whose cdr is a proper-list, or the symbol nil,
without circles.

Ok, this is becomming a little less muddy... A list can have a single
element, the cdr of which is implicitly nil? For example:

(setq my-single-list (list 'a)) ;; ok
my-single-list ;; (a)
(car my-single-list) ;; a
(cdr my-single-list) ;; nil

However, a cons *cannot* have only a single element. Example:

(setq my-single-cons (cons 'a)) ;; error!

I'm looking at the elisp manual and it says: A "list" represents a
sequence of zero or more elements (which may be any Lisp objects).
Whereas the definition of cons is: A cons cell is a data object that
represents an ordered pair. That is, it has two slots, and each slot
"holds", or "refers to", some Lisp object.

I think I understand now. Thanks for your help!

-Jason

.



Relevant Pages

  • Re: cons and list behaviour
    ... A list is either a cons, or the symbol nil, which can also be printed as: ... A proper-list is either a cons whose cdr is a proper-list, or the symbol nil, ... It seems that the list notation works well with the cons notation, ... walls you build from the basic legoblocs. ...
    (comp.lang.lisp)
  • Re: reverse not working: CL-USER> (rvrs (1 2 3)) (((NIL . 3) . 2) . 1)
    ... (defun rvrs (lista) ... A list is either the symbol NIL, representing the empty list, ... or a CONS cell containing an element, followed a LIST containing the rest. ...
    (comp.lang.lisp)