schememultiple-valuer7rs

How to consume only the first returned value in Scheme?


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?


Solution

  • 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