How to consume only the first returned value in Scheme?

85 Views Asked by At

Given a Scheme function returning multiple values, for example:

(exact-integer-sqrt 5) ⇒ 2 1

How can I use only the first returned value, ignoring the other ones?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use call-with-values inside macro:

(define-syntax first-val
  (syntax-rules ()
    ((first-val fn)
     (car (call-with-values (lambda () fn) list)))))

(first-val (values 1 2 3 4))
(first-val (exact-integer-sqrt 5))

There are also define-values and let-values, if you know number of returned values.

(define-values (x y) (exact-integer-sqrt 5)) ;global

(let-values ([(x y z) (values 1 2 3)]) ;local
    x)

Source: R7RS report

0
On

Simply use let-values:

(let-values (((root rem) (exact-integer-sqrt 5)))
  root)

The above will extract both results in separate variables, and you can choose which one you need.