使用方案从列表中计算非零值

counting non-zero values from a list with scheme

我是 scheme 和这个网站的新手.. 我打扰了这个问题。请给我一种方法来编写一个方案函数来计算数字列表中有多少个非零值..

(non-zero '(4 1 0 2 0 1 3)) - 5

我对scheme一点都不熟悉。但这可以使用递归轻松实现。想象一个列表 [0,1,2,2,0,1]。您需要沿着列表向下走,依次查看每个元素,并在每次在列表中找到 0 时将计数器加一。

(define (count_zeroes numbers)
  (if (null? numbers) 0
      (+ 1 (count_zeroes (cdr numbers))))

你要考虑三种情况:

(define (non-zero numbers)
  (cond ((null? numbers) 0)              ; is the list empty? return zero
        ((not (= (car numbers) 0))       ; is the current element non-zero?
         (+ 1 (non-zero (cdr numbers)))) ; add 1 to the counter and recur
        (else                            ; otherwise
         (non-zero (cdr numbers)))))     ; skip to the next element

或者如果您的解释器支持它,更惯用的解决方案是使用高阶过程:

(define (non-zero numbers)
  (count (lambda (n) (not (zero? n)))
         numbers))

无论哪种方式,它都按预期工作:

(non-zero '(4 1 0 2 0 1 3))
=> 5