Chapter 4
Program Control
Multiple Values
The execution of an expression can yield one value, more than one value, or no values at all. This capability is called multiple values.
Multiple values are generated by the
function values
. They are received
by the bindings of let
declarations
and define constant
and define
variable
definitions.
Many statements will return multiple values if the last expression they execute returns multiple values. Similarly, a function will return all the values of the last subexpression it executes.
define method return-three-values (a, b, c)
values(a, b, c)
end method return-three-values; begin let (foo, bar, baz) = return-three-values (1, 2, 3); list (foo, bar, baz) end ⇒ #(1, 2, 3)
Each expression in the argument list of a function call supplies only one argument to the function call. That argument is the first value returned by the expression. Additional values returned by the expressions are ignored.
list (return-three-values(1, 2, 3),
return-three-values(1, 2, 3),
return-three-values(1, 2, 3))
⇒
#(1, 1, 1)
Multiple values can be used to perform parallel binding:
begin let x = 10; let y = 20; let (x, y) = values (y, x); list (x, y); end ⇒ #(20, 10)
The following rules apply when matching up an expression that returns multiple values with a binding declaration or definition that receives multiple values.
- If there are the same number of bindings and values, the bindings are initialized to the corresponding values.
- If there are more bindings than there are values, the extra bindings are initialized
to
#f
. (If a binding is typed,#f
must be an instance of its type or an error is signaled.) - If there are more values returned than there are bindings, the excess values are placed
in a sequence that is used as the initial value for rest-binding or discarded if there is
no rest-binding.
begin let (one, #rest nums) = return-three-values(1, 2, 3); nums; end ⇒ #(2, 3)
- If there is a rest-binding but there are no excess values, rest-binding is initialized to an empty sequence.
Errata: In the published book,
a comma is missing between one
and #rest
.