0

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?

Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75

2 Answers2

1

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

Martin Půda
  • 7,353
  • 2
  • 6
  • 13
1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386