【问题标题】:about racket remainder expected params关于球拍剩余预期参数
【发布时间】:2025-12-01 15:25:01
【问题描述】:

最近,我正在学习 scp,但我遇到了一个奇怪的问题:

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)
  1. 操作系统:win10
  2. lang: 球拍 v6.10.1

它告诉余数期望一个整数参数 我想我给了一个整数,而不是一个列表。所以有人可以告诉我我的代码有什么问题。我陷入了困境。提前致谢。

【问题讨论】:

    标签: lisp racket sicp


    【解决方案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)))))
    

    【讨论】: