Jay
Jay

Reputation: 36

Confused with "do" variables in Racket code

Don't understand why "a" and "b" work in the code ? should we define var "a" and "b" before "do" ?

(define v1 3)
(define v2 2)
(do ((a 1 (+ a v1))
     (b 2 (+ b v2)))
  ((>= a b) (if (= a b) 'YES 'NO)))

Upvotes: 1

Views: 118

Answers (2)

Sylwester
Sylwester

Reputation: 48745

There are no control flow operations other than procedure calls. do is just a macro. The R5RS report gives an implementation:

(define-syntax do
  (syntax-rules ()
    ((do ((var init step ...) ...)
       (test expr ...)
       command ...)
     (letrec
         ((loop
           (lambda (var ...)
             (if test
                 (begin
                   (if #f #f)
                   expr ...)
                 (begin
                   command
                   ...
                   (loop (do "step" var step ...)
                         ...))))))
       (loop init ...)))
    ((do "step" x)
     x)
    ((do "step" x y)
     y)))

Your code turns into something like this:

(let loop ((a 1) (b 2))
  (if (>= a b)
      (if (= a b) 'YES 'NO)
      (loop (+ a v1) (+ b v2))))

Upvotes: 0

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

After (do the local variables for the do loop are defined:

  • (a 1 (+ a v1)) meaning: define local loop variable a with starting value 1 and assigning (+ a v1) to a at the beginning of a new round
  • (b 2 (+ b v2)) meaning: define local loop variable b with starting value 2 and assigning (+ b v2) to b at the beginning of a new round

So, a and b are defined in the do loop.

Upvotes: 2

Related Questions