我目前正在学习 scp book 的练习 1.3。这是问题的描述:
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
我试图用下面的代码解决它
(define (square x) (* x x))
(define (sq2largest a b c)
((define large1 (if (> a b) a b))
(define small (if (= large1 a) b a))
(define large2 (if (> c small) c small))
(+ (square large1) (square large2))))
当我在 mit-scheme 中运行它时,出现以下错误:
;Can't bind name in null syntactic environment: large1 #[reserved-name-item 13]
谷歌搜索这个错误不会产生很多结果。有谁知道我的代码有什么问题? (我不熟悉Scheme)
最佳答案
我将尝试分解您的 sq2largest 过程的结构:
基本结构是:
(define (sq2largest a b c)
; Body)
你写的正文是:
((define large1 (if (> a b) a b)) ; let this be alpha
(define small (if (= large1 a) b a)) ; let this be bravo
(define large2 (if (> c small) c small)) ; let this be charlie
(+ (square large1) (square large2)) ; let this be delta) ; This parentheses encloses body
因此,Body 的结构如下:
(alpha bravo charlie delta)
翻译为:“将 bravo、charlie 和 delta 作为参数传递给 alpha。”
现在,alpha 被告知接受一堆参数,但在为 large1 保留的命名空间内,没有为任何参数提供任何参数......即方案遇到一个无法绑定(bind)任何变量的空句法环境。
括号在 Scheme(以及大多数,如果不是全部的话,Lisps)中很重要,因为它们定义了过程的范围并强制[1] 操作的应用顺序。
[1] “不会产生歧义,因为运算符始终是最左边的元素,整个组合由括号分隔。” http://mitpress.mit.edu/sicp/full-text/sicp/book/node6.html
关于scheme - 错误 : Can't bind name in null syntactic environment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14907879/