guile-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

while break and continue


From: Kevin Ryde
Subject: while break and continue
Date: Fri, 30 May 2003 10:00:51 +1000
User-agent: Gnus/5.090019 (Oort Gnus v0.19) Emacs/21.2 (gnu/linux)

I was going to add some words to the manual about break and continue
in a while loop, but noticed continue doesn't do what I might have
thought.  For instance,

        (define n 0)
        (while (begin
                 (format #t "test ~a\n" n)
                 (< n 2))
               (format #t "body ~a\n" n)
               (set! n (1+ n))
               (if #t
                   (continue))
               (format #t "unreachable ~a\n" n))

prints

        test 0
        body 0
        test 1
        body 1
        test 2
        unreachable 2
        test 2
        unreachable 2
        test 2

whereas I might have hoped "unreachable" would indeed have been
unreachable, and the test wouldn't be evaluated again once false (at
n=2).

Is a throw the best way for continue to extricate itself from the
body?  I take it that's the intention.  If so perhaps something like
the following (only tested a bit),

(define while
  (procedure->memoizing-macro
   (lambda (expr env)
     (let* ((break-key     (gensym " while break-key"))
            (continue-key  (gensym " while continue-key"))
            (break-proc    (lambda (value) (throw break-key value)))
            (continue-proc (lambda ()      (throw continue-key))))
       `(catch ',break-key
               (lambda ()
                 (do ()
                     ((not ,(cadr expr)))
                   (let ((break    ,break-proc)
                         (continue ,continue-proc))
                     (catch ',continue-key
                            (lambda ()
                              ,@(cddr expr))
                            noop))))
               (lambda args (cadr args)))))))

Each while loop gets its own break and continue keys and procedures,
to allow those procedures to be used from inner nested loops.  The new
bindings are only for the body forms, maybe they should be available
to the condition expression too.

Not really a thing of beauty, and probably not fast.  A good reason
not to use unstructured stuff like "continue" I guess :-).




reply via email to

[Prev in Thread] Current Thread [Next in Thread]