The While Loop in Racket

Viewed 2837

Write a procedure in Racket that act like the "while loops" in languages like Java. A while loop takes two pieces of code to run: a condition and a body. it runs the body, then tries the condition again, running the body again if it's true. This continues until the condition returns false.

this is how I started on it: then I got stuck.

(define (while condition body)
   (when (true? condition)
       (cons (proc body) (proc (rest body)))
2 Answers

condition and body are procedures, so you have have to call them.

After calling the body, you have to call while recursively to repeat.

(define (while condition body)
  (when (condition)
    (body)
    (while condition body)))

You don't need true?, since when just checks whether the condition is #f or not.

in Scheme while must be implemented with macro to avoid evaluation of args

(define-syntax while
  (syntax-rules ()
    ((_ pred b1 ...)
     (let loop () (when pred b1 ... (loop))))))
Related