filter - 从 Racket 的子列表中删除所有 ()
问题描述
我需要有以下程序交互:
(clean'(1 (2 () (3 () 4))()()(()) 5)) → (1 (2 (3 4)) 5)
这是我到目前为止所拥有的
define (emptyClear theList)
(cond ((null? theList) '())
((null? (car theList)) (emptyClear (cdr theList)))
(else (cons (car theList) (emptyClear (cdr theList))))))
(define (clean tree)
(cond ((null? tree) '())
((not (list? (car tree))) (cons (car tree) (prune (cdr tree))))
(cons (emptyClear (car tree)) (prune (cdr tree)))))
但这给了我:-> (1 5)
作为输出。
我该如何解决这个问题?
解决方案
从示例中,任务似乎不仅仅是从树中删除空列表,而是继续执行此操作直到可能(因为'(())
)不是空列表,但它仍然被删除)。
这是一个可能的解决方案,已使用 DrRacket 进行了测试。
(define (my-empty? x)
(cond ((null? x) #t)
((list? x) (andmap my-empty? x))
(else #f)))
(define (clean x)
(cond ((null? x) '())
((not (list? x)) x)
((my-empty? (car x)) (clean (cdr x)))
(else (cons (clean (car x)) (clean (cdr x))))))
(clean '(1 (2 () (3 () 4))()()((())) 5)) ;=> '(1 (2 (3 4)) 5)
推荐阅读
- node.js - 只执行一项测试
- android - 在 TextFormField 中,maxLength 获得了可访问性焦点 - 为什么?
- kubernetes - filebeat 不能在一个实例中使用多个输入/输出配置文件吗?
- ios - 当应用程序已在 Apple Store 上发布时通过 TestFlight 分发
- googletest - 来自模拟对象的方法未被调用
- javascript - 为什么当我在 PHP 中使用 json 数组设置 cookie 时,是否显示 % 符号?
- c# - 如何从 Untiy 中找到国家名称
- django - TemplateSyntaxError:模板和静态文件
- java - 返回第 K 个到最后一个:不正确的输出
- tensorflow - 为什么我的 MakeFile 路径设置出现“没有这样的文件或目录”错误?