guile-user
[Top][All Lists]
Advanced

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

Re: loop translations (was: Re: language translator help)


From: Neil Jerram
Subject: Re: loop translations (was: Re: language translator help)
Date: 28 Apr 2002 19:21:51 +0100
User-agent: Gnus/5.0808 (Gnus v5.8.8) Emacs/20.7

>>>>> "John" == John W Eaton <address@hidden> writes:

    John>   (let for ((i 1))
    John>     (call-with-current-continuation
    John>      (lambda (break)
    John>        (if (<= i 5)
    John>            (begin
    John>              (display i)
    John>              (newline)
    John>              (if (= i 2)
    John>                  (break (if #f #f)))
    John>              (for (+ 1 i)))))))

    John> This works, but seems quite complex to me.  Is there a
    John> simpler way?

Depends what you mean by simpler.  There are certainly ways that you
could make it _look_ simpler :-).

For example, if you had a general `for' macro defined like this:

(define-macro (for varspec . body)
  (let ((varsym (car varspec))
        (vari (cadr varspec))
        (varf (caddr varspec)))
    `(catch 'break
       (lambda ()
         (let loop ((,varsym ,vari))
           (catch 'continue
             (lambda ()
               (if (<= ,varsym ,varf)
                   (begin
                     ,@body
                     (throw 'continue))))
             (lambda ignored
               (loop (+ ,varsym 1))))))
       (lambda ignored
         (if #f #f)))))

then the translation for this particular case could look like this:

(for (i 1 4)
  (display i)
  (newline)
  (if (= i 2)
      (throw 'break)))

Note that I've used catch and throw rather than call/cc here.  call/cc
is slow and expensive in Guile; wherever the jump is once-only and
upwards-only, it's more efficient to use catch/throw.

    John> Here is another:

    John>   for i = 1:4
    John>     if (i < 4)
    John>       disp ("foo-i-hithere");
    John>       if (i == 2)
    John>       continue;
    John>       endif
    John>     endif
    John>     disp (i);
    John>   endfor

(for (i 1 4)
  (if (< i 4)
      (begin
        (display "foo-i-hithere\n")
        (if (= i 2)
            (throw 'continue))))
  (display i)
  (newline))

Does this help?

        Neil




reply via email to

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