Chuong Nguyen
Chuong Nguyen

Reputation: 67

Write a function COUNT-NUMBERS that counts the number of numbers in a list

I'm begginer at LISP, and I have a question need your help.

Write a function COUNT-NUMBERS that counts the number of numbers in a list,and return " NO NUMBER" if there is no number in the list

For example, for a list: (A 2.3 B C 4 5), it returns 3.

I've tried with the following code, but it doesn't work . Could you help me to figure out? Moreover, I don't know how to return "NO NUMBER" if there is no number in the list.

(defun count-numbers (x)
      (cond ((null x) 0)
                ((numberp x) 1)
                (t (+(count-numbers (car x))(count-numbers (cdr x))))))

Thanks in advance,

Upvotes: 0

Views: 951

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139411

This would be a tail-recursive version. Somehow you have to check what to return.

(defun count-numbers (list &optional (n 'no-number))
  (cond ((null list) n)
        ((numberp (first list))
         (count-numbers (rest list)
                        (if (eq n 'no-number)
                            1
                          (1+ n))))
        (t (count-numbers (rest list) n))))

With a LOOP you can write that this way:

(defun count-numbers (list)
  (loop for element in list
        count (numberp element) into n
        finally (return (if (zerop n) 'no-number n))))

Upvotes: 1

shizhz
shizhz

Reputation: 12531

You could to define a inner helper function to do the counting, and check the result to decide what to return in the main function:

(defun number-counter (lst)
  (labels ((do-count (l)
                 (cond ((null l) 0)
                       ((numberp (car l)) (+ 1 (do-count (cdr l))))
                       (t (do-count (cdr l))))))
    (let ((r (do-count lst)))
      (if (= r 0) 'NO-NUMBER r))))

Upvotes: 1

Related Questions