[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Lisp Help!!



Ken,
  If I understand you correctly you have created a lisp "tree", which can
contain nil as an item.  Now a cons cell has the following structure:

      +---------+---------+    +---------+---------+
      |   Car   |   Cdr --+--> |   Car   |   Cdr --+--> NIL
      +----|----+---------+    +----|----+---------+
           |                        |
           V                        V
      NIL or List               NIL or List
      
      
So, on looking at a given cell, if the Cdr (i.e. (Rest my-list)) is NIL
you are at the end of a list of sub list. If it is not NIL you have (at
least) another cons cell in the list.

To recursively traverse the list  you can do something like:

      		
(defun trav-tree (the-list &optional (level 0))    
  (declare (notinline trav-tree))
  (loop ; loop for each cons cell in the list
    (let ((me (first the-list)))
      (cond
       ((null me) (return))             ; return if the car is empty (we are at 
the end of the list)

       ((listp me)                      ; go down a level if there is a sub-tree
        (trav-tree me (1+ level)))

       (t  (format t "~%")              ; do something if this is a real element
           (dotimes (i level)
             (format t "=="))
           (format t "~S" me)))

      ; go to the next cons cell -- if there is one
      (setf the-list (rest the-list))
      (unless the-list
        (return)))))


(defvar *the-1st-tree* '(3 2 (1 2 4 (2) 4) ((3 1) 8)))

(trav-tree *the-1st-tree*)

3
2
==1
==2
==4
====2
==4
====3
====1
==8

Now it seems like you want to lay out this tree as a sort of "template",
which the user will fill in.  In this case it, since a standard empty
list can be represented by nil, and the "rest" of an empty list is also
nil, you are asking for trouble using standard lists.  You have two
choices, either create a new kind of linkable object and write the 
commands to parse it, OR, just define a place-holder:

> (defvar *the-2nd-tree* '(3 2 (1 2 4 (2) 4) ((:empty-place :empty-place) 8)))

> (trav-tree *the-2nd-tree*)

3
2
==1
==2
==4
====2
==4
====:EMPTY-PLACE
====:EMPTY-PLACE
==8

Since:
> (eq :empty-place nil)
F

If you are going to spend a lot of time going in multiple directions 
throughout this structure, you probably want to bite the bullet and write
a more appropriate structure.  A cons cell is convenient, but it is not
the be all and end all of lisp data structures in many applications.

             Jeffrey
             

======================================
Jeffrey Kane, MD
Kane Biomedical Systems
Boston, MA

Internet    jbk@world.std.com
Compuserve  74206,640
AppleLink   D0738

[Don't take life too seriously... it's not like anyone gets out of it alive.]
      			
      	
          
      
          

Sent: 4/5/1995, 22:7