chris kelly
chris kelly

Reputation: 21

recursive list function in lisp that finds number of times a was present in list

;Question 3

(defun listcheck(lst)
  (cond
   ((not (null lst))
    (cond
     ((eq (car lst) 'a) (+ (listcheck (cdr lst)) 1))
     ( T (listcheck (cdr lst)))
     )
    )
   )
  0
  )

this function prints out 0 at all times not sure where im going wrong any input would help

Upvotes: 0

Views: 50

Answers (1)

Barmar
Barmar

Reputation: 780798

It's printing 0 because the function ends with 0, outside the cond. So it returns this in all cases, not just the base of the recursion. That should only be returned when lst is null.

(defun listcheck(lst)
  (cond ((null lst) 0)
        ((eq (car lst) 'a) (+ (listcheck (cdr lst)) 1))
        (T (listcheck (cdr lst)))))

Upvotes: 2

Related Questions