为什么这段代码在Scheme中不起作用?
(define a 42)
(set! 'a 10)
(define a 42)
(define (symbol) 'a)
(set! (symbol) 10)
(define a (cons 1 2))
(set! (car a) 10)
我尝试在 DrScheme 中运行它们,但它们不起作用。 为什么?
(define a 42)
(set! 'a 10)
(define a 42)
(define (symbol) 'a)
(set! (symbol) 10)
(define a (cons 1 2))
(set! (car a) 10)
I tried running them in DrScheme and they don't work. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
想想定! 是一种特殊形式,如define,它不评估其第一个操作数。 您告诉方案解释器按照您编写的方式设置该变量。 在您的示例中,它不会将表达式 'a 计算为单词 a。 相反,它将查找名为“'a”的变量绑定(或者取决于您的解释器可能会在此之前中断,因为我认为'a不是有效的绑定)。
对于最后一组表达式,如果要设置一对中的汽车,请使用函数 (set-car!pair val),该函数的工作方式与任何方案函数类似,因为它会评估其所有操作数。 它接受两个值,一对和一些方案值,并改变这对,以便汽车现在指向方案值。
例如。
Think of set! is a special form like define which does not evaluate its first operand. You are telling the scheme interpreter to set that variable exactly how you write it. In your example, it will not evaluate the expression 'a to the word a. Instead, it will look for a variable binding named "'a" (or depending on your interpreter might just break before then since I think 'a is not a valid binding).
For the last set of expressions, if you want to set the car of a pair, use the function (set-car! pair val) which works just like any scheme function in that it evaluates all of its operands. It takes in two values, a pair and some scheme value, and mutates the pair so that the car is now pointing to the scheme value.
So for example.
因为 set 的第一个参数! 可以这么说,是一个变量名,而不是“左值”。
对于最后一种情况,请使用 (set-car! a 10)。
Because the first argument of set! is a variable name, not an "lvalue", so to speak.
For the last case, use (set-car! a 10).
问题出在 (set! 'a 10) 上,因为您不应该引用符号 a。
听起来你想学习Scheme,但你不懂Lisp,是吗? 如果是这样,我强烈建议尝试 Clojure,因为它是一种更容易学习的 Lisp。 在 Common Lisp 和 Scheme 中,我都未能掌握阅读器、求值、符号、特殊形式、宏等之间的交互,因为这些东西似乎都以错综复杂的方式交互,但我终于在 Clojure 中真正理解了它们。 尽管它是新的,但我发现 Clojure 文档实际上比我发现的任何 Scheme 或 CL 文档都更清晰。 从 http://clojure.blip.tv/ 中的视频开始,然后阅读 clojure 中的文档。组织。
The issue is with (set! 'a 10), as you shouldn't be quoting the symbol a.
It sounds like you're trying to learn Scheme, and you don't know Lisp, yes? If so, I strongly recommend trying Clojure as an easier to learn Lisp. I failed to grasp the interaction between the reader, evaluation, symbols, special forms, macros, and so forth in both Common Lisp and Scheme because those things all seemed to interact in tangled ways, but I finally really understand them in Clojure. Even though it's new, I found Clojure documentation is actually clearer than anything I found for Scheme or CL. Start with the videos at http://clojure.blip.tv/ and then read the docs at clojure.org.