# Looping in Scheme

(define loop
(lambda (x proc)
(when (not (= x 0))
(eval proc)
(loop (- x 1) proc))))


Is this the best way to create a loop function in Scheme?

There are a number things a seasoned Schemer would do differently:

1. Use a more descriptive name for the procedure, such as call-n-times.
2. Use times or count (or n, if you call your procedure call-n-times) instead of x.
3. Use zero? instead of (= ... 0).
4. Use unless instead of (when (not ...) ...).
5. Not use eval, but instead pass in a lambda and invoke it directly.
6. Do the tail recursion using a named let so you don't have to re-pass the proc argument.

Putting all this together, we get:

(define (call-n-times n proc)
(let loop ((n n))
(unless (zero? n)
(proc)
(loop (- n 1)))))


Bonus points: allow the caller to pass additional arguments and pass them through to the given procedure:

(define (call-n-times n proc . args)
(let loop ((n n))
(unless (zero? n)
(apply proc args)
(loop (- n 1)))))