Make my own while loop using "define-syntax-rule"

465 Views Asked by At

I am trying to create my own while-loop in racket using the "define-syntax-rule". I want it to be procedural based, so no helper functions (i.e. just using lambda, let, letrec, etc.).

I have this, but it gives me some sort of lambda identifier error.

(define-syntax-rule (while condition body)
  (lambda (iterate)
    (lambda (condition body) ( (if condition)
                                   body
                                   iterate))))

I want it to be so I can use it like a regular while loop For Example:

(while (x < 10) (+ x 1))

Calling this will(should) return 10 after the loop is done.

How can my code be fixed to do this?

1

There are 1 best solutions below

0
user448810 On

Here is the while from my Standard Prelude, along with an example of its use:

Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define-syntax while
    (syntax-rules ()
      ((while pred? body ...)
        (do () ((not pred?)) body ...))))
> (let ((x 4))
    (while (< x 10)
      (set! x (+ x 1)))
    x)
10

You should probably talk to your instructor about your misconceptions involving Scheme.