list - 如何在计划中不返回任何内容

标签 list scheme lisp cons

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

相关文章:

compiler-construction - 了解编译器中递归闭包的建模

list - 如何在 Scala 中通过预处理将列表转换为可变映射?

python - 如何在python中将整数列表写入二进制文件

for-loop - 在 Racket /方案中展开 'for' 循环的宏?

scheme - 通过 Racket 创建文件

list - 如何在 lisp 中编写递归?

java - java中ArrayList的indexOf()返回-1

Python 按特定定义的规则对项目进行排序

scheme - 将列表转换为 Chicken 方案中的循环列表?

replace - Lisp:多级搜索和替换