'(list 1 2) 在 Scheme 中是什么意思?
What does '(list 1 2) means in Scheme?
我正在研究 SICP,在第 2.2.2 节的开头,它给出了以下代码:(cons '(list 1 2) (list 3 4)))
并说它构造了一个类似于 ((1 2) 3 4)
的列表。但是当我将它输入到 DrRacket 中时(实际上我在这里使用的是 Racket),它会生成 '((list 1 2) 3 4)
并且如果我写 (cons (list 1 2) (list 3 4))
那么它就没问题了。我知道在方案中 '(1 2)
等于 (list 1 2)
但 '(list 1 2)
是什么意思?
应该是"a list consisting of the atom list, the atom 1, and the atom 2"的意思。在 Scheme 评估列表(单引号阻止)之前,它不会将 "list" 与任何其他字符串区别对待。
符号 'foo
生成一个名为 foo 的符号。
符号 '(foo bar)
生成一个列表,其中包含两个名为 foo
和 bar
的符号。
以相同的方式'(list foo bar)
列出三个符号。符号 'list
恰好被称为 list
.
现在 (list 'foo 'bar)
列出了两个符号 foo
和 bar
.
Scheme 有一个方便的语法来表示数据文字:在任何表达式前加上 '(单引号),表达式将不被计算,而是作为数据返回
更多信息:
http://courses.cs.washington.edu/courses/cse341/04wi/lectures/14-scheme-quote.html
修复输出样式
首先,当您在 DrRacket 中使用 #!racket
语言时,默认的打印方式不是打印它的表示形式,而是打印一个计算结果相同的表达式。您可以从菜单 语言 >> 选择语言 中将其关闭。您 select 显示详细信息 并在输出样式下 select 写入
按下 运行 后,在计算 'test
时,您将得到输出 test
.
表达式中有错别字
在section 2.2.2中有一个表达式(cons (list 1 2) (list 3 4))
。它与您在问题 (cons '(list 1 2) (list 3 4))
中所写的 不同。虽然表达式 (list 1 2)
应用具有值 1
和 2
的过程 list
并因此变为 (1 2)
,但表达式 '(list 1 2)
只是 return 引用数据(list 1 2)
不变。
因此:
(cons (list 1 2) (list 3 4)) ; ==> ((1 2) 3 4)
(cons '(list 1 2) (list 3 4)) ; ==> ((list 1 2) 3 4)
'(cons '(list 1 2) (list 3 4)) ; ==> (cons '(list 1 2) (list 3 4))
我正在研究 SICP,在第 2.2.2 节的开头,它给出了以下代码:(cons '(list 1 2) (list 3 4)))
并说它构造了一个类似于 ((1 2) 3 4)
的列表。但是当我将它输入到 DrRacket 中时(实际上我在这里使用的是 Racket),它会生成 '((list 1 2) 3 4)
并且如果我写 (cons (list 1 2) (list 3 4))
那么它就没问题了。我知道在方案中 '(1 2)
等于 (list 1 2)
但 '(list 1 2)
是什么意思?
应该是"a list consisting of the atom list, the atom 1, and the atom 2"的意思。在 Scheme 评估列表(单引号阻止)之前,它不会将 "list" 与任何其他字符串区别对待。
符号 'foo
生成一个名为 foo 的符号。
符号 '(foo bar)
生成一个列表,其中包含两个名为 foo
和 bar
的符号。
以相同的方式'(list foo bar)
列出三个符号。符号 'list
恰好被称为 list
.
现在 (list 'foo 'bar)
列出了两个符号 foo
和 bar
.
Scheme 有一个方便的语法来表示数据文字:在任何表达式前加上 '(单引号),表达式将不被计算,而是作为数据返回
更多信息:
http://courses.cs.washington.edu/courses/cse341/04wi/lectures/14-scheme-quote.html
修复输出样式
首先,当您在 DrRacket 中使用 #!racket
语言时,默认的打印方式不是打印它的表示形式,而是打印一个计算结果相同的表达式。您可以从菜单 语言 >> 选择语言 中将其关闭。您 select 显示详细信息 并在输出样式下 select 写入
按下 运行 后,在计算 'test
时,您将得到输出 test
.
表达式中有错别字
在section 2.2.2中有一个表达式(cons (list 1 2) (list 3 4))
。它与您在问题 (cons '(list 1 2) (list 3 4))
中所写的 不同。虽然表达式 (list 1 2)
应用具有值 1
和 2
的过程 list
并因此变为 (1 2)
,但表达式 '(list 1 2)
只是 return 引用数据(list 1 2)
不变。
因此:
(cons (list 1 2) (list 3 4)) ; ==> ((1 2) 3 4)
(cons '(list 1 2) (list 3 4)) ; ==> ((list 1 2) 3 4)
'(cons '(list 1 2) (list 3 4)) ; ==> (cons '(list 1 2) (list 3 4))