You can pass two return values directly to a function with call-with-values. To store them together, use list to collect them into one value.
Receive two values as two arguments
Run this complete example in the Playground.
(call-with-values
(lambda () (values 3 4))
(lambda (a b) (+ (* a a) (* b b))))Result
25call-with-values first calls (lambda () (values 3 4)) with no arguments. That procedure returns two values, 3 and 4.
It then calls the second procedure with those values as separate arguments. The parameters a and b receive 3 and 4, so the sum of their squares is 25.
The first procedure is called the producer, and the second is the consumer. A value packet means all the values returned by one call. Here, it contains two numbers that the consumer receives separately.
Store the results in a list
Run this complete example to save the two numbers under one name.
(define saved
(call-with-values (lambda () (values 3 4)) list))
savedResult
(3 4)Here, list is the consumer. It receives two arguments and builds one list. define stores that single list in saved.
values returns the values to the caller. To keep them as data, collect them into a list or vector. A list with two elements is one value, even though it contains two numbers.
Check how many values the next call needs
The consumer must accept the number of arguments the producer returns. The first example uses two parameters. list accepts any number of arguments.
Ordinary call arguments, conditions, variable initializers, and the right-hand side of an assignment each need one value. Receive multiple results through call-with-values before using them in those places. You can still store a producer procedure in a variable and pass it to call-with-values.
(values) returns zero values. A consumer that accepts zero arguments can receive them. You can also use it where results are discarded, such as before the final expression in begin.
Try a change
In the first example, replace (values 3 4) with (list 3 4). Will the two-parameter consumer still work?
Answer
It reports E302, an argument-count error. The producer now returns one list, so the consumer receives one argument. Its two parameters require two arguments. Use values to return the two numbers separately.
The multiple-values manual explains where each value count is accepted. See procedures for fixed and variable argument counts.