是什么导致 Scheme 中出现未绑定变量错误?

What causes an unbound variable error in Scheme?

我已经开始使用 SICP,而且我是 Scheme 的新手。我试过调试这段代码,甚至将它与类似的解决方案进行了比较。

(def (myFunc x y z)
    (cond ((and (<= x y) (<= x z)) (+ (* y y) (* z z)))
          ((and (<= y x) (<= y z)) (+ (* x x) (* z z)))
          (else (+ (* x x) (* y y)))))

这个函数returns两个最大数的平方和。

当我运行这个时,解释器给出“;Unbound variable: y”。您能否解释一下此错误背后的原因?

非常感谢帮助:)

Scheme 中的函数定义原语称为define,而不是def

实际上,整个 (def ...) 表达式被视为对 def 的函数调用。因此需要找到它的参数值。第一个参数 (myFunc x y z) 是一个函数调用,因此需要找到它的参数值。显然,您的实现想要首先找出 y 的值。

The R5RS standard says "The operator and operand expressions are evaluated (in an unspecified order) and the resulting procedure is passed the resulting arguments."

您的实现很可能首先选择最右边的参数,这导致首先评估 (<= x y)(因为评估 condand [=29= 的特殊规则]特殊形式),y最右边的位置。