This is the mail archive of the guile@sourceware.cygnus.com mailing list for the Guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Q: throw and catch


Ivan Toshkov <ivant@ifao.net> writes:

> I am trying to find a realization of throw and catch in Scheme.
> I know about call-with-current-continuation, but couldn't think of a good
> way to hide it.
> 
> Can anyone show me an implementation?

Here's one.  Note, though, that Guile's catch takes a third handler
argument as well.

(define catch #f)
(define throw #f)

(let ((catch-chain '()))

  (define (local-catch tag thunk)
    (call-with-current-continuation
     (lambda (c)
       (let ((local-chain (cons (cons tag c) catch-chain))
	     (old-chain '()))
	 (dynamic-wind
	     (lambda ()
	       (set! old-chain catch-chain)
	       (set! catch-chain local-chain))
	     thunk
	     (lambda ()
	       (set! catch-chain old-chain)))))))
  
  (define (local-throw tag value)
    (cond ((assq tag catch-chain) => (lambda (entry) ((cdr entry) value)))
	  (else (error "Uncaught throw"))))
  
  (set! catch local-catch)
  (set! throw local-throw))

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]