(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:
call-n-times
.times
or count
(or n
, if you call your procedure call-n-times
) instead of x
.zero?
instead of (= ... 0)
.unless
instead of (when (not ...) ...)
.eval
, but instead pass in a lambda and invoke it directly.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)))))