2016-04-13 52 views
0

我是新方案,在這個網站..我打斷了這個問題。請給我一種方法來編寫一個計劃函數來計算一個數字列表中有多少非零值。從方案列表中計數非零值

(非零'(4 1 0 2 0 1 3)) - 5

回答

0

你必須要考慮三種情況:

(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 
+0

yeahh ..它那樣做:)謝謝 –

-1

我對計劃根本不熟悉。但是這可以很容易地使用遞歸來實現。想象一下列表[0,1,2,2,0,1]。您需要沿着列表走下去,依次查看每個元素,並在每次在列表中找到0時增加一個計數器。

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

是啊謝謝..但在這裏,我們檢查的原子是一個非零值的條件? (用於檢查我們使用的零(= 0(汽車號))),這就是爲什麼我困惑,我們如何檢查原子是不是零? –