取出列表中所有出现的元素
Take out all occurences of element in list
我有这个代码:
(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',它将删除所有出现的它,因为它们在括号之外。所以,我无法从里面取出任何东西。
解决方案有点复杂,您必须使用模板来遍历列表列表。此外,最好使用 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)
我有这个代码:
(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',它将删除所有出现的它,因为它们在括号之外。所以,我无法从里面取出任何东西。
解决方案有点复杂,您必须使用模板来遍历列表列表。此外,最好使用 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)