\$\begingroup\$
\$\endgroup\$
(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?
asked Nov 14, 2015 at 9:58
1 Answer 1
\$\begingroup\$
\$\endgroup\$
There are a number things a seasoned Schemer would do differently:
- Use a more descriptive name for the procedure, such as
call-n-times
. - Use
times
orcount
(orn
, if you call your procedurecall-n-times
) instead ofx
. - Use
zero?
instead of(= ... 0)
. - Use
unless
instead of(when (not ...) ...)
. - Not use
eval
, but instead pass in a lambda and invoke it directly. - Do the tail recursion using a named
let
so you don't have to re-pass theproc
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)))))
answered Nov 14, 2015 at 16:39
lang-lisp