Determining the level of the item being searched

Given the list / tree of the form: (node1 (node2) (node3 (node4) (node5)) (node6)) I should be able to find out the depth at which the found node is located.

This is what I have done so far:

(defun search-it (lst level n) (cond ((null lst) nil) ((and (atom (car lst)) (equal (car lst) n)) level) ((atom (car lst)) (search-it (cdr lst) level n)) (t (cons (search-it (car lst) (+ 1 level) n) (search-it (cdr lst) level n))))) (defun search-node (ln) (search-it l 0 n)) 

For this specific implementation, I have the right solution, but what bothers me is that I cannot get rid of some nil lists. For instance:

  (search-node '(1 (2) (3 (4) (6) (7) (8 (9) (10)))) 6) (NIL (NIL 2 NIL (NIL NIL))) 

The solution is correct if we look at the root of the node at a depth of 0. Now, of course, I could add code to the search function of the node to remove everything but the solutions, I cannot help but feel that this is not the most elegant way to do this.

LE . The expected result should be a depth or list of depths if the number appears more than once.

Some point to someone? PS: lisp newbie

+4
source share
1 answer

Usually returns a list of depths. So, if the item is found, return a list of one depth. If you go to the first and the rest of the list, then not "cons", but "append".

Please note that your code does not find all depths.

 CL-USER 6 > (search-node '(6 (6)) 6) 0 
+2
source

All Articles