简体   繁体   English

试图在Dr. Racket中实现删除*?

[英]Trying to implement remove* in Dr. Racket?

(define (removeAll list-a list-b)
  (if (empty? list-b)
    list-a
    (apply
      (removeAll((remove (first list-b) list-a) (rest list-b)))
    )
  )
)

(removeAll '(abbccd) '(aca))

expected output is '(bbd) in this case 在这种情况下,预期输出为'(bbd)

I can use remove but I can't use remove* itself. 我可以使用删除但我不能使用删除*本身。 Currently I'm getting this error: application: not a procedure; expected a procedure that can be applied to arguments given: '(bbccd) arguments...: 目前我收到这个错误: application: not a procedure; expected a procedure that can be applied to arguments given: '(bbccd) arguments...: application: not a procedure; expected a procedure that can be applied to arguments given: '(bbccd) arguments...:

If you execute your program in DrRacket you will obtain the error message with a clear evidence of its reason: 如果您在DrRacket中执行程序,您将获得错误消息,并明确证明其原因:

在此输入图像描述

You see that the problem is inside: 你看到问题在里面:

((remove (first list-b) list-a) (rest list-b)))

The reason is that in scheme you cannot use the parentheses freely like in other languages: (+ 2 (+ 3 4)) is not equal to (+ 2 ((+ 3 4))) : the first expression is evaluated to 9, the second gives an error since ((+ 3 4)) is interpreted in this way: 原因是在方案中你不能像其他语言一样自由使用括号: (+ 2 (+ 3 4))不等于(+ 2 ((+ 3 4))) :第一个表达式被计算为9,第二个给出错误,因为((+ 3 4))以这种方式解释:

  1. Evaluate the inner form (expression) (+ 3 4) , that is apply the operation + to the arguments 3 and 4, producing 7. 评估内部形式(表达式) (+ 3 4) ,即将操作+应用于参数3和4,生成7。
  2. Since (+ 3 4) is inside another set of parentheses, than get the result and try to evaluate (7) as a form. 因为(+ 3 4)在另一组括号内,所以得到结果并尝试将(7)作为一个表格进行评估。 But 7 is not an operator (“not a procedure”, as the error message says), so an error is raised. 但是7 不是运算符(“不是过程”,如错误消息所示),因此会引发错误。

In your case, the result of remove is a list, and this cannot be used as an operator. 在您的情况下, remove的结果是一个列表,这不能用作运算符。

If you remove the double parentheses, in this way: 如果您删除双括号,以这种方式:

(removeAll (remove (first list-b) list-a) (rest list-b))

you will remove the first error, and you will see that there is another error, in particular: 你将删除第一个错误,你会发现还有另一个错误,特别是:

apply: arity mismatch;
 the expected number of arguments does not match the given number
  expected: at least 2
  given: 1
  arguments.:

Here is a possible solution: 这是一个可能的解决方案:

(define (removeAll list-a list-b)
  (if (empty? list-b)
      list-a
      (removeAll (filter (lambda (x) (not (eq? (first list-b) x))) list-a) (rest list-b))))

The function filter remove all the elements that do not satisfy the predicate. 函数filter删除所有不满足谓词的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM