Using "do" in a schema

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 fragment creates 01234, and the second - 5. What happens? What does an extra set of parentheses do? In addition, I used [(= i 50)] instead of ((= i 5)) . Are there any differences? Thanks!

+5
source share
2 answers

The general structure of the do form is as follows:

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

Paraphrasing http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-ZH-6.html#node_chap_5 , each iteration begins with a <test> score, if it evaluates the true value, <expression> are evaluated from left to right and last value if the result of the form do . In your second example, = will be evaluated as a boolean true, then I will be evaluated, and finally 5 is the return value of the form. In the first case (= i 5) this is a test, and the do form returns undefined. A typical way to write a loop would look something like this:

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

You do not need an explicit mutation of the loop variable, since it is processed by the <step> expression.

+11
source

In the first case ((= i 5)) functions as a test to complete. So the do loop repeats until i = 5.

In the second case (= i 5) is not a criterion. The do loop just executes the first form, which returns 5.

-

(In the attached comments), brackets are used interchangeably in some dialects of the pattern. It is sometimes considered idiomatic to use [] for parameters (i.e., for the parent).

+6
source

Source: https://habr.com/ru/post/1315011/


All Articles