2014-02-17 43 views
3

我在Scheme中分配了編程任務時遇到了一個小問題。我們得到的任務是創建一個函數,它只返回符合給定謂詞要求的對結構中的值。他們也將以同樣的配對結構返還,只需刪除違規條目即可。到目前爲止,我的代碼如下所示如何在計劃中使用缺點返回任何內容

(define (keep-if-all ia pred ls) 
(cond 
    ((null? ls) null) 
    ((pair? ls) 
    (cons 
    (keep-if-all pred (car ls)) 
    (keep-if-all pred (cdr ls)))) 
    ((pred ls) ls) 
    (else null))) 

問題是否則返回null,從而用null替換值而不是刪除它。

例如

(keep-if-all odd? (list 1 2 3 (cons 4 4) (list 1 2 3 4 5))) 

返回

(1() 3 (()) (1() 3() 5)) 

而不是期望的

(1 3() (1 3 5)) 

在正確的方向A戳將不勝感激

回答

1

只需添加一個諾特爾if那裏,

(define (keep-if-all pred ls) 
(cond 
    ((null? ls) '()) 
    ((pair? ls) 
    (let ((x (keep-if-all pred (car ls)))) 
     (if (or (not (null? x))    ; if something's left of (car ls) 
       ....)       ;  or if it was a pair, 
     (cons x (keep-if-all pred (cdr ls))) ; then, include x in the output 
     ....)))        ; else, don't include x in the output 
    ((pred ls) ls) 
    (else '()))) 

現在它按預期工作:

(keep-if-all odd? (list 1 2 3 (cons 4 4) (list 1 2 3 4 5))) 
;Value 15: (1 3() (1 3 5)) 
+0

它期望在這個意義上,分配有保留()左右成對或列出了完全消失 – Tenbin

+0

謝謝你這麼多的例子爲了幫助=)空白填滿了,得到了恰到好處的幫助=) – Tenbin