[plt-scheme] looping?

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Mon Jun 5 21:36:55 EDT 2006

On Jun 5, 2006, at 9:05 PM, Mike wrote:

> I know there is intended a lot of recursion for scheme,
> but is there looping? The REPL construct isn't recursive
> (my guess). How do you loop?
>
> (define *running* #t)
> (while *running*
>   (if (something-is-done)
>     (set! *running* #f)))

Define looping and I define loops for you :-)

Answer 1: A loop is a construct that doesn't allocate space for control 
state. In that case, you get this:

(define-syntax while
   (syntax-rules ()
     ((_ tst stmt ...)
      (letrec ((w (lambda () (when tst (begin stmt ...) (w))))) (w)))))

;; Use like this:
(define x 0)
(while (x . < . 10) (printf "~s\n" x) (set! x (+ x 1)))

Why? Because tail-recursive functions don't consume space for control 
state.

Answer 2: (Which is what you're not looking for yet) A loop is a 
construct that traverses a data structure and applies an action at each 
step (piece of data). Again, in Scheme, you define your own such 
looping construct:

(define (for-each-element-in-a-list a-list action)
  (cond
    ((pair? a-list) (action (car a-list)) (for-each-element-in-a-list 
(cdr a-list) action))
    (else (void))))

;; Use like this:
(for-each-element-in-a-list '(1 2 3) display)

-- Matthias



Posted on the users mailing list.