Just started learning lisp and I need to write a function, COUNTER, that would do as mentioned in the title. For example,
(COUNTER 'fizz '(fizz (buzz (fizz) (buzz fizz)) fizz))
should return 4
First try
I've written the following
(defun COUNTER (atom list)
(cond
((null list) 0)
((equal atom (first list)) (+ 1 (COUNTER atom (rest list))))
(t (COUNTER atom (rest list)))))
Which only counts the atom at the top most level (in the case of the example, my output is 2). What do I need to add to have it read the nested lists? I know I should be traversing the sublist and sum the results, but I'm not exactly sure which predicate I should be using and where exactly I should place it. I'm thinking right after
((equal atom (first list)) (+ 1 (COUNTER atom (rest list))))
Second try
I have tried the following to no avail
(defun COUNTER (target nest_list)
(cond ((null nest_list) 0)
(cond (atom (first nest_list) ((equal target (first nest_list)) (+ 1 (COUNTER target (rest nest_list)))))
(t (COUNTER target (first nest_list))))
(t (COUNTER target (rest nest_list)))))
I am receiving compilation errors from it. The logic to me seems to make sense. I'm testing to see whether the entity is an atom or a list, if atom, then see if it's equal and add 1, otherwise recur if it's a list. I'm not sure if I'm doing something wrong with the parenthesis placement or whether I'm allowed to use a cond within a cond like that.