Re: cons and list behaviour
- From: "Jason" <jemeade@xxxxxxxxx>
- Date: 26 Feb 2006 13:20:53 -0800
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
.
- Follow-Ups:
- Re: cons and list behaviour
- From: Frank Buss
- Re: cons and list behaviour
- References:
- cons and list behaviour
- From: Jason
- Re: cons and list behaviour
- From: Pascal Bourguignon
- cons and list behaviour
- Prev by Date: Re: cons and list behaviour
- Next by Date: Re: cons and list behaviour
- Previous by thread: Re: cons and list behaviour
- Next by thread: Re: cons and list behaviour
- Index(es):
Relevant Pages
|
|