[plt-scheme] puzzled about multiple value return

From: John Clements (clements at brinckerhoff.org)
Date: Fri Feb 3 14:07:09 EST 2006

On Feb 3, 2006, at 10:56 AM, pedro pinto 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?
>
> 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"))))))

Urk.  How about something like this:

(define (setup) 3)
(define (teardown) 4)

(define (helper thunk)
   (setup)
   (let ([results (call-with-values thunk list)])
     (teardown)
     (apply values results)))

(helper (lambda () (values 1 2 3)))

=>

Welcome to DrScheme, version 301.4-svn31jan2006.
Language: Pretty Big (includes MrEd and Advanced Student).
1
2
3
 >

In short, I think you're looking for 'call-with-values'. (I was a bit  
surprised to see that let-values doesn't support a varargs-like  
syntax, though.)

John Clements



-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2430 bytes
Desc: not available
URL: <http://lists.racket-lang.org/users/archive/attachments/20060203/70b66b5f/attachment.p7s>

Posted on the users mailing list.