我在 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)))
问题是 else 返回 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))
如能指出正确的方向,我们将不胜感激
最佳答案
只需在此处添加另一个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))
关于list - 如何在计划中不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21838405/