[plt-scheme] Why multiple values?

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Sun Dec 24 16:06:04 EST 2006

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


Posted on the users mailing list.