1

I need to write a function that counts all occurrences of a given atom inside of a list. This is what I have:

(defun my-count (a L)
    (cond
    ((null L) nil)
    ((equal a (car L))(+ 1 (my-count a (cdr L))))
    (t (my-count a(cdr L)))
    )
)

By my understanding this should work. However when I run a trace I find that when (equals a car L) evaluates to true it makes the recursive call but doesn't initialize the + 1. There is obviously something I am missing.

Shrp91
  • 173
  • 2
  • 5
  • 14

1 Answers1

3

The problem is your null condition. You are in a recursive addition, and when you're done you should add 0, not nil:

(defun my-count (a L)
  (cond
   ((null L) 0)
   ((equal a (car L)) (+ 1 (my-count a (cdr L))))
   (t (my-count a (cdr L)))))

such as

? (my-count 'x '(a x b))
1
? (my-count 'x '(a x  x b))
2
? (my-count 'x '(a b))
0
uselpa
  • 18,732
  • 2
  • 34
  • 52