[plt-scheme] finally

From: Eli Barzilay (eli at barzilay.org)
Date: Tue Dec 20 00:01:17 EST 2005

On Dec 19, Doug Orleans wrote:
> Eli Barzilay writes:
>  > On Dec 19, Doug Orleans wrote:
>  > > What is the PLT equivalent of Java's "finally"?  I think I could write
>  > > something using dynamic-wind, but is there a more efficient way to do
>  > > it if you just want to guard exits and not entrances?
>  > 
>  > You can give dynamic-wind `void' as a first argument.
> 
> Well, yes, I knew that, I was just wondering if there was something
> more efficient/idiomatic.  Anyway, here's my macro:
> 
>   (define-syntax try
>     (syntax-rules (finally)
>       ((_ expr catch-clause ... (finally finally-expr ...))
>        (dynamic-wind void
>            (lambda () (try expr catch-clause ...))
>            (lambda () finally-expr ...)))
>       ((_ expr ((exn? exn) catch-expr ...) ...)
>        (with-handlers ((exn? (lambda (exn) catch-expr ...))
>                        ...)
>          expr))))

If you're already going down to the `with-handlers' level, why not
just use it for the finally clause?  Something like:

  (define-syntax try
    (syntax-rules (finally)
      ((_ expr catch-clause ... (finally finally-expr ...))
       (let ([finalizer (lambda () finally-expr ...)])
         (with-handlers ((exn? (lambda (exn) (finalizer) catch-expr ...))
                         ...
                         (void (lambda (e) (finalizer) (raise e))))
           (begin0 expr (finalizer)))))))

(which is a bit different than your version.)

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.