使用“做".在计划中 [英] Using "do" in Scheme

查看:104
本文介绍了使用“做".在计划中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CODE SNIPPET 1和CODE SNIPPET 2有什么区别?

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))) 

第一个代码段产生01234,第二个代码段产生5.这是怎么回事?多余的括号是做什么用的?另外,我已经看到使用了[(= i 50)]而不是((= i 5)).有区别吗?谢谢!

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!

推荐答案

do表单的一般结构如下:

The general structure of a do form is like this:

(do ((<variable1> <init1> <step1>)
     ...)
    (<test> <expression> ...)
  <command> ...)

改写 http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-ZH-6.html#node_chap_5 ,每次迭代都从评估<test>开始,如果评估为真值,则为<expression> s从左到右求值,最后一个值作为do表单的结果返回.在您的第二个示例中,=将被评估为布尔值true,然后将对i进行评估,最后5是表单的返回值.在第一种情况下,(= i 5)是测试,并且do形式返回未定义的值.编写循环的通常方法是这样的:

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 the do 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 the do form returns an undefined value. The usual way to write a loop would be more like this:

(do ((i 0 (+ i 1)))
    ((= i 5) i)      ; maybe return the last value of the iteration
  (display i))

您不需要显式更改循环变量,因为这是由<step>表达式处理的.

You don't need an explicit mutation of the loop variable as this is handled by the <step> expression.

这篇关于使用“做".在计划中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆