我在 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))