Reputation: 177
The matrix-qr
function in Racket's math library outputs two values. I know about call-with-values to put both output values into the next function you want.
However, how can I take each individual output and put define some constant with that value? The QR function outputs a Q matrix and an R matrix. I need something like:
(define Q ...)
(define R ...)
Also, how could I just use one of the outputs from a function that outputs two values?
Upvotes: 1
Views: 316
Reputation: 43852
The usual way to create definitions for multiple values is to use define-values
, which pretty much works like you’d expect.
(define-values (Q R) ; Q and R are defined
(matrix-qr (matrix [[12 -51 4]
[ 6 167 -68]
[-4 24 -41]])))
There is also a let
equivalent for multiple values, called let-values
(as well as let*-values
and letrec-values
).
Ignoring values is harder. There is no function like (first-value ...)
, for example, because ordinary function application does not produce a continuation that can accept multiple values. However, you can use something like match-define-values
along with the _
“hole marker” to ignore values and simply not bind them.
(match-define-values (Q _) ; only Q is defined
(matrix-qr (matrix [[12 -51 4]
[ 6 167 -68]
[-4 24 -41]])))
It is theoretically possible to create a macro that could either convert multiple values to a list or simply only use a particular value, but in general this is avoided. Returning multiple values should not be done lightly, which is why, for almost all functions that return them, it wouldn’t usually make much sense to use one of the values but ignore the other.
Upvotes: 2