[plt-scheme] puzzled about multiple value return

From: Ryan Culpepper (ryan_sml at yahoo.com)
Date: Fri Feb 3 14:13:01 EST 2006

--- pedro pinto <pedro.e.pinto at gmail.com> wrote:

> hi there,
> 
> I have a little helper function that does something like this:
> 
> (define (helper thunk)
>   (setup)
>   (let ((result (thunk))
>      (teardown)
>       result))
> 
> Meaning my helper wraps a call to a thunk with some setup/teardown
> actions and returns whatever thunk returned. If thunk raises an
error
> however, I do not want for teardown to be called.
> 
> Assuming I have no control over thunk, how do I make the helper
> cope with possible multiple return values from thunk?

You can use call-with-values, values, and apply:

(define (helper thunk)
  (setup)
  (call-with-values thunk
                    (lambda results
                      (teardown)
                      (apply values results))))

Ryan

> Here is my attempt:
> 
> (define (helper thunk)
>   (let ((success #t))
>     (dynamic-wind
>         (lambda () (printf "Setup~n"))
>         (lambda ()
>           (with-handlers (((lambda ex #t)
>                            (lambda (exn)
>                              (set! success #f)
>                              (raise exn))))
>             (thunk)))
>         (lambda()
>           (if success
>               (printf "Teardown~n"))))))
> 
> > (helper (lambda () (values 1 2 3)))
> Setup
> Teardown
> 1
> 2
> 3
> 
> > (helper (lambda () 1))a
> Setup
> Teardown
> 1
> 
> > (helper (lambda () (error "Abort") (values 1 2 3)))
> Setup
> > Abort
> 
> This seems to work, but its ugly. Is there a nicer solution?
> 
> -pp
> 
> 
> 
> 
> -pp
> > _________________________________________________
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> 


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


Posted on the users mailing list.