简体   繁体   中英

Function to count number of 0 in given arguments in lisp

I want to create a function in LISP to count the number of 0 in given arguments

Ex

(count_number_of_0 '(1 0 5 9 0 0 0 7 1 0) ) 

Output : 5

Here is an implementation in Racket, which is a lisp-family language. It would be quite easy to translate into Common Lisp (but a little more verbose in CL):

(define make-counter
  (λ (v same?)
    (λ (l)
      ((λ (c)
         (c c 0 l))
       (λ (c a t)
         (if (null? t)
             a
             (c c (if (same? (first t) v) (+ a 1) a) (rest t))))))))

(define count-zeros
  (make-counter 0 =))

And now

> (count-zeros '(1 2 0 3 4 0))
2

one way is:

(defun count-number-of-0 (lst &optional (cnt 0)) ;counter starts at zero
  (if lst
    (if (and (numberp (car lst)) ;better verify that element is a number
             (= 0 (car lst)))
        (progn
          (setq cnt (+ cnt 1))
          (count-number-of-0 (cdr lst) cnt))
        (count-number-of-0 (cdr lst) cnt))
    cnt)) ;return counter

This should work in all implementations of common-lisp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM