Distinguish list and generic lisp atom

I have a main clisp function that I do that returns the number of atoms in a list. The problem I am facing is that I need it to increase for the atoms in the list that is in the list, instead of seeing the list as 1 element in the list.

The real question, in my opinion, is how do you differentiate in your code, is an element a list or an atom ? If I can do this, I can send lists to another function to add and return the number of atoms that they contain.

Clean like dirt? :)

I have an example:

(defun list_length (a) (cond ((null a) 0) (t (+ 1 (list_length (cdr a)))))) 

This works fine if the parent list has no built-in lists, for example, '(1 2 3 (4 5) 6) will return 5. I need it to include 4 and 5 instead of list (4 5) as one.

Thank you for your help.

John


EDIT:

 (defun list_length (a) (cond ((null a) 0) ((listp (car a)) (list_length (car a))) (t (+ 1 (list_length (cdr a)))))) 

 [18]> (list_length '(1 2 3 (4 5) 6)) 1. Trace: (LIST_LENGTH '(1 2 3 (4 5) 6)) 2. Trace: (LIST_LENGTH '(2 3 (4 5) 6)) 3. Trace: (LIST_LENGTH '(3 (4 5) 6)) 4. Trace: (LIST_LENGTH '((4 5) 6)) 5. Trace: (LIST_LENGTH '(4 5)) 6. Trace: (LIST_LENGTH '(5)) 7. Trace: (LIST_LENGTH 'NIL) 7. Trace: LIST_LENGTH ==> 0 6. Trace: LIST_LENGTH ==> 1 5. Trace: LIST_LENGTH ==> 2 4. Trace: LIST_LENGTH ==> 2 3. Trace: LIST_LENGTH ==> 3 2. Trace: LIST_LENGTH ==> 4 1. Trace: LIST_LENGTH ==> 5 5 [19]> (dribble) 
+4
source share
2 answers

(listp foo) will return t if foo is a list and nil otherwise.

So you can make your list_length functions handle nested lists by adding the following case to your cond :

 ((listp (car a)) (+ (list_length (car a)) (list_length (cdr a)))) 
+4
source

ATOM is the predicate you are asking for.

I recommend using FLATTEN, the standard procedure for smoothing lists in lists - here I present one implementation.

 (defun flatten (x) "descend into the supplied list until an atom is hit. append the atom to the flattened rest" (if (endp x) x (if (atom (car x )) (append (list (car x)) (flatten (cdr x))) (append (flatten (car x)) (flatten (cdr x )))))) 

Flatten returns the list: you can run LENGTH on the list to see how many ATOMS you have launched.

+3
source

All Articles