使用“do”在方案中
代码片段 1 和代码片段 2 有什么区别?
;CODE SNIPPET 1
(define i 0)
(do ()
((= i 5)) ; Two sets of parentheses
(display i)
(set! i (+ i 1)))
;CODE SNIPPET 2
(define i 0)
(do ()
(= i 5) ; One set of parentheses
(display i)
(set! i (+ i 1)))
第一个代码片段生成 01234,第二个代码片段生成 5。这是怎么回事?额外的括号有什么作用?另外,我还看到使用 [(= i 50)]
而不是 ((= i 5))
。有区别吗?谢谢!
What is the difference between CODE SNIPPET 1 and CODE SNIPPET 2?
;CODE SNIPPET 1
(define i 0)
(do ()
((= i 5)) ; Two sets of parentheses
(display i)
(set! i (+ i 1)))
;CODE SNIPPET 2
(define i 0)
(do ()
(= i 5) ; One set of parentheses
(display i)
(set! i (+ i 1)))
The first code snippet produces 01234 and the second produces 5. What is going on? What does the extra set of parentheses do? Also, I have seen [(= i 50)]
used instead of ((= i 5))
. Is there a distinction? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
do 形式的一般结构如下:
释义 http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-ZH-6.html#node_chap_5,每次迭代都从评估< 开始/code>,如果计算结果为真值,则从左到右计算
<表达式>
,最后一个值作为do
形式的结果返回。在第二个示例中,=
将被评估为布尔值,表示 true,然后 i 将被评估,最后 5 是表单的返回值。在第一种情况下,(= i 5)
是测试,do
形式返回未定义的值。编写循环的通常方法更像是这样:您不需要循环变量的显式突变,因为这是由
表达式处理的。The general structure of a do form is like this:
Paraphrasing http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-6.html#node_chap_5, each iteration begins by evaluating
<test>
, if it evaluates to a true value,<expression>
s are evaluated from left to right and the last value is returned as the result of thedo
form. In your second example=
would be evaluated as a boolean meaning true, then i would be evaluated and at last 5 is the return value of the form. In the first case(= i 5)
is the test and thedo
form returns an undefined value. The usual way to write a loop would be more like this:You don't need an explicit mutation of the loop variable as this is handled by the
<step>
expression.在第一种情况下,((= i 5)) 充当终止测试。因此,重复 do 循环直到 i = 5。
在第二种情况下,(= i 5) 不是测试。 do 循环只执行第一个形式,返回5。
--
(根据所附评论)括号在方案的某些方言中是可以互换的。有时认为使用 [] 作为参数(即父级 do)是惯用的。
In the first case, ((= i 5)) functions as a test for termination. So the do loop is repeated until i = 5.
In the second case, (= i 5) isn't a test. The do loop simply executes the first form, which returns 5.
--
(Per the attached comments) brackets are interchangeable in some dialects of scheme. It is sometimes considered idiomatic to use [] for parameters (i.e. to the parent do).