2013-06-25 35 views
2

我無法寫方案的函數返回一個列表奇數數量,而無需使用任何賦值語句奇數號碼的功能。我試圖使用謂詞奇?爲好。任何幫助/提示將不勝感激。方案編寫返回列表中的

例如:(賠率「(1 2 3 4 5)//返回3

此外,該列表是整數

回答

1

不論您是否使用(?R6RS)計劃或球拍,這兩個工作:

(define (odds lst) 
    (length (filter odd? lst))) 

(define l '(1 2 3 4 5 6 7 8 9 10)) 
(odds l) 
4

好吧,如果不能使用任何賦值語句,你仍然可以使用的。內置的這個程序特別是count將很好地在球拍工作:

(define (odds lst) 
    (count odd? lst)) 

...但我猜你應該從頭開始實現該解決方案的一些提示尋找解決方案。你自己,填充了空白:

(define (odds lst) 
    (cond (<???>     ; if the list is empty 
     <???>)    ; then how many odd numbers are in it? 
     ((odd? <???>)   ; if the first element is odd 
     (<???> (odds <???>))) ; then add one and advance recursion 
     (else     ; otherwise 
     (odds <???>))))  ; just advance the recursion 

無論如何,它按預期工作:

(odds '(1 2 3 4 5)) 
=> 3 
0

由於低水平我可以得到它:

(define odds 
    (lambda (lst) 
    (cond ((empty? lst) 0) 
      ((not (= 0 (modulo (car lst) 2))) (+ 1 (odds (rest lst)))) 
      (else (odds (cdr lst)))))) 
0

這裏是另一個單線程

(define (odds L) 
(reduce + 0 (map (lambda (x) (if (odd? x) 1 0)) L))) 
0

這裏是返回計數基於謂詞的任何功能的功能:

(define (counter-for predicate) 
    (define (counting list) 
    (if (null? list) 
     0 
     (+ (if (predicate (car list)) 1 0) 
      (counting (cdr list))))) 
    counting)) 

所使用,如:

(define odds (counter-for odd?)) 

[更多選項]這裏是一個漂亮的遞歸解決方案

(define (odds list) 
    (if (null? list) 
     0 
     (+ (if (odd? (car list)) 1 0) 
     (odds (cdr list))))) 

這裏是一個尾遞歸的解決方案:

(define (odds list) 
    (let odding ((list list) (count 0))) 
    (if (null? list) 
     count 
     (odding (cdr list) 
       (+ count (if (odd? (car list)) 1 0)))))) 

下面是計算基於謂詞任何常規:

(define (count-if predicate list) 
    (if (null? list) 
     0 
     (+ (if (predicate (car list)) 1 0) 
     (count-if predicate (cdr list)))))