guile-user
[Top][All Lists]
Advanced

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

Re: escaping from a recursive call


From: Olivier Dion
Subject: Re: escaping from a recursive call
Date: Wed, 09 Nov 2022 12:55:42 -0500

On Wed, 09 Nov 2022, Damien Mattei <damien.mattei@gmail.com> wrote:
> but in the general case  , i want a macro that can do it on any function
> (i'm not sure it can be done because the continuation have to be captured
> just before the call to the function and be inlined at the good
> place....)

I'm not aware of any control mechanism that are implicit in Guile.  You
almost always have to deal with a continuation object.  However, nothing
prevent you to invent your own control flow wrapper.

For example:
--8<---------------cut here---------------start------------->8---
(define my-prompt (make-prompt-tag))

(define-syntax-rule (return-now x)
  (abort-to-prompt my-prompt x))

(define (wrap-this procedure)
  (let ((inside? #f))
    (lambda args
      (if inside?
          (apply procedure args)
          (begin
            (set! inside? #t)
            (let ((ret
                   (call-with-prompt my-prompt
                     (lambda ()
                       (apply procedure args))
                     (lambda (_ x)
                       x))))
              (set! inside? #f)
              ret))))))

(define-syntax define-interruptible
  (syntax-rules ()
    ((_ (name formals ...) body ...)
     (define name
       (wrap-this
        (lambda (formals ...) body ...))))))

(define-interruptible (foo n)
  (cond
   ((= n 0) 'end0)
   ((= n 7) (return-now 'end7))
   (else
    (cons n (foo (1- n))))))

(pk (foo 5))
(pk (foo 10))
--8<---------------cut here---------------end--------------->8---

There's probably other way of doing so that I'm not aware of.

-- 
Olivier Dion
oldiob.dev



reply via email to

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