关于球拍剩余预期参数
about racket remainder expected params
最近在学习sicp,遇到一个奇怪的问题:
Error:
remainder: contract violation
expected: integer?
given: '(3 4 5 6)
argument position: 1st
other arguments...:
2
这是我的代码
(define (same-parity sample . other)
(if (null? other)
(cons sample '())
(if (= (remainder sample 2) (remainder (car other) 2))
(cons (car other) (same-parity sample (cdr other)))
(same-parity sample (cdr other)))))
(same-parity 1 2 3 4 5 6)
- os:win10
- lang: 球拍 v6.10.1
它告诉余数期望一个整数参数
我想我给了一个整数来余数而不是列表。所以有人可以告诉我我的代码有什么问题。我进退两难了。提前致谢。
发生此错误是因为您的过程对未知数量的多个参数进行操作 - 这就是 .
在声明过程时的含义,而 other
被解释为参数列表。它在调用过程时传递正确的参数,但我们第一次调用递归时,它失败了。
一个解决方案是确保我们始终将过程应用于多个参数,而不是将 list 作为第二个参数传递,这就是您的代码现在正在做的,导致错误。试试这个:
(define (same-parity sample . other)
(if (null? other)
(cons sample '())
(if (= (remainder sample 2) (remainder (car other) 2))
(cons (car other) (apply same-parity sample (cdr other)))
(apply same-parity sample (cdr other)))))
最近在学习sicp,遇到一个奇怪的问题:
Error: remainder: contract violation expected: integer? given: '(3 4 5 6) argument position: 1st other arguments...: 2
这是我的代码
(define (same-parity sample . other)
(if (null? other)
(cons sample '())
(if (= (remainder sample 2) (remainder (car other) 2))
(cons (car other) (same-parity sample (cdr other)))
(same-parity sample (cdr other)))))
(same-parity 1 2 3 4 5 6)
- os:win10
- lang: 球拍 v6.10.1
它告诉余数期望一个整数参数 我想我给了一个整数来余数而不是列表。所以有人可以告诉我我的代码有什么问题。我进退两难了。提前致谢。
发生此错误是因为您的过程对未知数量的多个参数进行操作 - 这就是 .
在声明过程时的含义,而 other
被解释为参数列表。它在调用过程时传递正确的参数,但我们第一次调用递归时,它失败了。
一个解决方案是确保我们始终将过程应用于多个参数,而不是将 list 作为第二个参数传递,这就是您的代码现在正在做的,导致错误。试试这个:
(define (same-parity sample . other)
(if (null? other)
(cons sample '())
(if (= (remainder sample 2) (remainder (car other) 2))
(cons (car other) (apply same-parity sample (cdr other)))
(apply same-parity sample (cdr other)))))