[plt-scheme] Why multiple values?

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Sun Dec 24 18:36:47 EST 2006

> So, here's another basic question: If I know that f returns multiple 
> values, but I don't know how many, but I do know that I only care about, 
> say, the first two values, can I get them as x and y? Can I gain access 
> to all the values, even if I don't know in advance how many there are?

Hi Gregory,

Yes; the technique uses the related idea of making a function that can 
take in an arbitrary number of arguments.

For example:

> (define mylist
     (lambda args
> (mylist 3 1 4 1 5 9 2 6)
(3 1 4 1 5 9 2 6)

Notice that there aren't any parens around 'args' here.  This is 
intentional, and it's what allows us to capture all the arguments in the 
argument list.

This, combined with using CALL-WITH-VALUES, can let us do what you're 

> (require (lib "list.ss"))
> (define-syntax first-two
     (syntax-rules ()
       [(_ expr)
        (call-with-values (lambda () expr)
                          (lambda args (list (first args)
                                             (second args))))]))
> (first-two (values 1 2 3 4 5))
(1 2)

I wrapped this in some syntax just to make it a little nicer to write that 
last FIRST-TWO expression.

Best of wishes!

Posted on the users mailing list.