我有这段代码:
(define remove
(λ (x y)
(cond
((null? y) '())
((eq? x (car y)) (delete x (cdr y)))
(else (cons (car y) (delete x (cdr y))))
)))
Input: (remove 'c '(w((x)(c q)(((o))))w))
这不会进入内括号内。如果我尝试删除' w',它将删除所有出现的内容,因为它们在括号外。所以,我无法从内部取出任何东西。
答案 0 :(得分:1)
解决方案稍微复杂一点,您必须使用该模板遍历列表列表。此外,最好使用equal?
代替eq?
,请参阅documentation以了解差异。接下来是一个可能的实现,我冒昧地将参数重命名为更有意义的东西:
(define remove
(λ (ele lst)
(cond
((null? lst) '()) ; if the list is empty then we're done
((not (pair? (car lst))) ; if the first element is an atom
(if (equal? (car lst) ele) ; check if it's the one we're looking for
(remove ele (cdr lst)) ; if so we skip over it, eliminating it
(cons (car lst) (remove ele (cdr lst))))) ; otherwise we add it
(else (cons (remove ele (car lst)) ; else advance recursion
(remove ele (cdr lst))))))) ; over both `car` and `cdr`
现在它按预期工作:
(remove 'c '(w ((x) (c q) (((o)))) w))
=> '(w ((x) (q) (((o)))) w)