2
\$\begingroup\$
(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
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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)))))
answered Nov 14, 2015 at 16:39
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.