第一:racket/scheme 打印出列表程序组合的合同违反错误
first: contract violation error in racket/scheme for printing out a combination of list procedures
我正在编写一个包含 2 个表达式的过程,如果有一种方法可以使用 first、rest、cons 通过 exp2 创建 exp1(当我们用 'sss 替换 exp2 时),那么 returns 生成 exp1 所需的代码。
例如,这是我想要制作的。
(find-in '(e r t) '(e t) ) => '(cons (first sss) (rest (rest sss)))
我的代码适用于很多测试用例,但是当我 运行 通过
(find-in '(a '(((v)) l) (f g)) '( (v g) l a))
它returns这个错误:
first: contract violation
expected: (and/c list? (not/c empty?))
given: 'g
当我尝试 运行 这个测试用例时出现同样的错误:
(find-in '(x a (x y)) '(z a (b)))
;supposed to return #f
到目前为止,这是我的代码:
(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))))
我很困惑我在编码时错过了哪个条件或者是否存在逻辑错误。可能出了什么问题?
我觉得你的最后一个条款不合适。当你对最后一个子句使用特殊的 else
标记时,你是在说“这里没有什么要测试的,如果你已经做到了这一点,就无条件地执行它的主体”。因此,就 cond
而言,您的下一个表达式 (list? exp1)
不是测试:它会针对副作用进行评估,并丢弃结果。然后下一个表达式也被评估,无论 exp1
是否是一个列表。
如果你想让这个条件成为 exp1
是否是一个列表,你应该删除开头多余的 else
(并且可能在末尾添加一个 else
子句到 return #f
如果 none 个案例匹配)。
我正在编写一个包含 2 个表达式的过程,如果有一种方法可以使用 first、rest、cons 通过 exp2 创建 exp1(当我们用 'sss 替换 exp2 时),那么 returns 生成 exp1 所需的代码。
例如,这是我想要制作的。
(find-in '(e r t) '(e t) ) => '(cons (first sss) (rest (rest sss)))
我的代码适用于很多测试用例,但是当我 运行 通过
(find-in '(a '(((v)) l) (f g)) '( (v g) l a))
它returns这个错误:
first: contract violation
expected: (and/c list? (not/c empty?))
given: 'g
当我尝试 运行 这个测试用例时出现同样的错误:
(find-in '(x a (x y)) '(z a (b)))
;supposed to return #f
到目前为止,这是我的代码:
(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))))
我很困惑我在编码时错过了哪个条件或者是否存在逻辑错误。可能出了什么问题?
我觉得你的最后一个条款不合适。当你对最后一个子句使用特殊的 else
标记时,你是在说“这里没有什么要测试的,如果你已经做到了这一点,就无条件地执行它的主体”。因此,就 cond
而言,您的下一个表达式 (list? exp1)
不是测试:它会针对副作用进行评估,并丢弃结果。然后下一个表达式也被评估,无论 exp1
是否是一个列表。
如果你想让这个条件成为 exp1
是否是一个列表,你应该删除开头多余的 else
(并且可能在末尾添加一个 else
子句到 return #f
如果 none 个案例匹配)。