SICP Exercise 4.9 do for while until

Exercise 4.9.  Many languages support a variety of iteration constructs, such as doforwhile, and until. In Scheme, iterative processes can be expressed in terms of ordinary procedure calls, so special iteration constructs provide no essential gain in computational power. On the other hand, such constructs are often convenient. Design some iteration constructs, give examples of their use, and show how to implement them as derived expressions.

SOLUTION

The code and tests are here.

I have implemented the following expressions:

do-while
do-until
for
while

The 'do-while' construct can be as follows:

(do
  (<one or more statements>)
  while (condition)
)

Use the while block construct to convert it as follows:

(begin
  <statements>
  (while (condition)
  <statements>
  )
)

The 'do-until' construct can be as follows:

(do
  (<one or more statements>)
  until (condition)
)

Use the while block construct to convert it as follows:

(begin
  <statements>
  (while (not (condition))
    <statements>
  )
)

The 'for' construct can be as follows:

(for (count-var <start>) (count-var <end>) inc
  (<one or more statements>)
)

where the variable 'count-var' is available for use inside the statement block and 'inc' is a one-argument proc that increments what is supplied to it. The user of the 'for' construct must supply a definition for the proc inc.

The derived expression for this would be:

(begin
  (define count-var <start>)
  (define (for-block)
    (if (<= count-var <end>)
      (begin
        <statements>
        (set! count-var (inc count-var))
        (for-block)
      )
      'done
    )
  )
  (for-block)
)

which is the same as:

(begin
  (define count-var <start>)
  (define for-block
    (lambda ()
      (if (<= count-var <end>)
        (begin
          <statements>
          (set! count-var (inc count-var))
          (for-block)
        )
        'done
      )
    )
  )
  (for-block)
)

The 'while' construct can be as follows:

(while (condition)
  <one or more statements>
)

; The derived expression for this would be:

(define (while-block)
  (if (condition)
    (begin
      <statements>
      (while-block)
    )
    'done
  )
)
(while-block)

which is the same as:

(define while-block
  (lamdba ()
    (if (condition)
      (begin
        <statements>
        (while-block)
      )
      'done
    )
  )
)
(while-block)

Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions