0

I am doing the exercise.4.9 of the sicp and I am trying to implement a syntax of the "for statement" which looks like the others would see in the c++:

(for (((i 0) (j 1))
      (< (+ i j) 10)
      ((i (+ i 1))))
     (display "i:")
     (display i)
     (display "\n")
     (display "j:")
     (display j)
     (display "\n"))

the syntax looks like:

(for ((initial-statement) (predicate-statement) (updating-statement)) (for-body))

and what I have generated is like:

((lambda ()
   (define j 1)
   (define i 0)
   (define inner-loop
     (if (< (+ i j) 10)
         (begin (display "i:")
                (display i)
                (display "\n")
                (display "j:")
                (display j)
                (display "\n")
                (set! i (+ i 1))
                (inner-loop))))
   (inner-loop)))

And I got an error saying that the first inner-loop invocation was trying to approach an unbound variable,

I am wondering what does the correct code I should generate look like?

Liu Weibo
  • 434
  • 5
  • 16

1 Answers1

2

As @Rainer mentioned in the comments, your definition of inner-loop is incorrect.

A function in scheme is defined as: (define (name ...args) body)

Or if there are no arguments: (define (name) body)

The following works:

((lambda ()
   (define j 1)
   (define i 0)
   (define (inner-loop)
     (if (< (+ i j) 10)
         (begin (display "i:")
                (display i)
                (display "\n")
                (display "j:")
                (display j)
                (display "\n")
                (set! i (+ i 1))
                (inner-loop))))
   (inner-loop)))
merlyn
  • 2,273
  • 1
  • 19
  • 26