0

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?

kmgauthier
  • 85
  • 1
  • 2
  • 5
  • 1
    Your desired syntax doesn’t really make any sense, for a few reasons. First of all, `(x < 10)` doesn’t make sense, since Scheme uses prefix function application, so it would need to be `(< x 10)`. Second of all, where is `x` bound? Your current code doesn’t make that clear. Third of all, `(+ x 1)` doesn’t mutate `x`, it just produces a new number, just like `x + 1` would do in a C-like language. You would need to do `(set! x (+ x 1))` to emulate `x += 1`. Without those clarifications, it’s hard to answer your question at all, even with your attempted code sample. – Alexis King Feb 26 '17 at 23:39
  • Maybe you should have a look at an implementation of SRFI-42 "Eager Comprehensions". – Michael Vehrs Feb 27 '17 at 08:22

1 Answers1

2

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.

user448810
  • 17,381
  • 4
  • 34
  • 59