[plt-scheme] Why multiple values?

From: michael rice (nowgate at yahoo.com)
Date: Sun Dec 24 16:11:10 EST 2006

Suppose you needed a function that simulates the
tossing of a pair of dice. You might be interested in
the total of the two

;single die toss
(define (die)
  (+ (random 6) 1))

;pair toss - return sum
(define (roll-two)
  (+ (die) (die))

or you may need the separate values

;pair toss - return individual die values 
(define (roll-two)
  (values die die))

See call-with-values for how to use values returned
with (values ...)

It all depends on what you want to do whether you need
to use (values ...) or not.

Michael

--- Carl Eastlund <cce at ccs.neu.edu> wrote:

> On 12/24/06, gregory.woodhouse at sbcglobal.net
> <gregory.woodhouse at sbcglobal.net> wrote:
> > In the cases like Danny's example, I've usually
> returned a list, as in
> >
> > (list (car x) (cdr x))
> 
> Sure, that works too, though it allocates a list
> that takes up space,
> must be destructured, and is not actually relevant
> to the problem.
> 
> > and, unless I'm misunderstanding you, the obious
> way to apply a function to a list of values sems to
> me to be map, as in
> >
> > (map (lambda (x) (* x x)) (list 1 2 3))
> >
> > On the other hand, if I want to do something
> similar with values, I'd have to write
> >
> > (call-with-values () (values 1 2 3) (lambda (x y
> z) (list (* x x) (* y y) (* z z))))
> >
> > and that's what I don't get. Here, I need to
> replicate the same expression three times.
> 
> That's not what I meant.  I don't mean applying a
> function multiple
> times to get multiple results.  I mean calling a
> function just once,
> but producing multiple values.  Like a division
> function that returns
> both a quotient and a remainder.  One computation
> produces multiple
> values; producing them from separate function calls
> would require
> performing the actual division twice.  So the
> function must either
> produce multiple values, or construct a compound
> structure like a cons
> or a list to return them in.  Many programmers
> prefer not to construct
> an arbitrary, irrelevant structure like a list for a
> non-list problem,
> so they use multiple values.
> 
> -- 
> Carl Eastlund
> _________________________________________________
>   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.