首页 > 解决方案 > 从 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)作为输出。

我该如何解决这个问题?

标签: filtertreeracketsublist

解决方案


从示例中,任务似乎不仅仅是从树中删除空列表,而是继续执行此操作直到可能(因为'(()))不是空列表,但它仍然被删除)。

这是一个可能的解决方案,已使用 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)

推荐阅读