[英]I'm trying to write a function in racket (delete-all xx elt) which returns a new list with all occurrences of elt removed
This is what i have but it only works if the elt appear at the start of the list这就是我所拥有的,但只有当 elt 出现在列表的开头时才有效
(define (delete-all xx elt)
(cond ((null? xx) null)
((equal? elt (car xx)) (delete (cdr xx) elt))))
You're missing an extra case: what happens if the current element is not the one you want to delete?你错过了一个额外的案例:如果当前元素不是你想要删除的元素,会发生什么? Here's the general idea of what needs to be done, I'm not giving you a straight answer because this looks like homework (you should use the homework
tag in your question).这是需要做什么的一般想法,我没有给你一个直接的答案,因为这看起来像家庭作业(你应该在你的问题中使用homework
标签)。 Better fill-in the blanks yourself:最好自己填空:
(define (delete-all xx elt)
(cond ((null? xx) ; base case: empty list
null) ; return the empty list
((equal? elt (car xx)) ; current element needs to be removed
<???>) ; ignore current element and make recursive call
(else ; current element needs to be added to the list
(<???> (car xx) <???>)))) ; add current element and make recursive call
Also, don't call delete
in your answer, given that this is a recursive solution, you need to call delete-all
instead, but with appropriate arguments to keep the recursion going until the base case is reached.另外,不要在您的答案中调用delete
,因为这是一个递归解决方案,您需要调用delete-all
,但使用适当的参数来保持递归直到达到基本情况。 Hint : what about cons
and cdr
?提示: cons
和cdr
怎么样?
You could also use filter
, that is if you're allowed to use higher order functions :您也可以使用filter
,也就是说,如果您可以使用高阶函数:
(define (delete-all xx elt)
(filter (lambda (y) (not(eq? xx y))) elt))
(define (delete-all xx elt)
remove* xx elt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.