简体   繁体   English

第一:用于打印列表程序组合的球拍/方案中的合同违反错误

[英]first: contract violation error in racket/scheme for printing out a combination of list procedures

I was writing a procedure that takes 2 expressions, and if there is a way for exp1 to be created through exp2 (when we replace exp2 with 'sss) using first, rest, cons, it then returns the code needed to produce exp1.我正在编写一个采用 2 个表达式的过程,如果有一种方法可以通过 exp2 创建 exp1(当我们用'sss 替换 exp2 时)首先使用 rest,cons,然后返回生成 exp1 所需的代码。

For example, this is what I would want to produce.例如,这就是我想要制作的。

(find-in '(e r t) '(e t) ) => '(cons (first sss) (rest (rest sss)))

My code works for a lot of the test cases but when I ran through我的代码适用于很多测试用例,但是当我运行

(find-in '(a '(((v)) l) (f g)) '( (v g) l a))

It returns this error:它返回此错误:

first: contract violation
  expected: (and/c list? (not/c empty?))
  given: 'g

The same error shows up when I try running this test case:当我尝试运行这个测试用例时出现同样的错误:

(find-in '(x a (x y)) '(z a (b))) 
;supposed to return #f

This is my code so far:到目前为止,这是我的代码:

(define find-in
  (lambda (exp2 exp1)
    (cond
      ((equal? exp2 exp1) 'sss)
      ((null? exp2) #f)
      ((not (list? exp2)) #f)
      ((find-in (first exp2) exp1) (repl 'sss '(first sss) (find-in (first exp2) exp1)))
      ((find-in (rest exp2) exp1) (repl 'sss '(rest sss) (find-in (rest exp2) exp1)))
      (else (list? exp1)
            (if
             (and (find-in exp2 (first exp1)) (find-in exp2 (rest exp1)))
             (list 'cons (find-in exp2 (first exp1)) (find-in exp2 (rest exp1)))
             #f) #f))))

I am confused as to which condition I missed when I coded or if there was a logic error.我很困惑我在编码时错过了哪个条件,或者是否存在逻辑错误。 What could have gone wrong?可能出了什么问题?

Your last clause doesn't look right to me.你的最后一个条款对我来说不合适。 When you use the special else token for your last clause, you are saying "There's nothing to test here, execute the body of this unconditionally if you've made it this far".当您对最后一个子句使用特殊的else标记时,您是在说“这里没有什么可测试的,如果您已经做到这一点,则无条件执行它的主体”。 Thus, your next expression, (list? exp1) , is not a test as far as cond is concerned: it is evaluated for side effects, and the results discarded.因此,就cond而言,您的下一个表达式(list? exp1)不是测试:它是针对副作用进行评估的,结果将被丢弃。 Then the next expression is also evaluated, whether exp1 was a list or not.然后下一个表达式也被评估,无论exp1是否是一个列表。

If you want to make this conditional on whether exp1 is a list, you should remove the excess else at the beginning (and probably add an else clause to the end to return #f if none of your cases matched).如果你想以exp1是否为列表为条件,你应该在开头删除多余的else (并且可能在末尾添加一个else子句以在没有匹配的情况下返回#f )。

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

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