【问题标题】:How to consume only the first returned value in Scheme?如何只消费 Scheme 中的第一个返回值?
【发布时间】:2021-11-18 20:35:47
【问题描述】:

给定一个返回多个值的 Scheme 函数,例如:

(exact-integer-sqrt 5) ⇒ 2 1

如何只使用第一个返回值,而忽略其他返回值?

【问题讨论】:

标签: scheme multiple-value r7rs


【解决方案1】:

您可以在宏内部使用call-with-values

(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))

如果您知道返回值的数量,还有define-valueslet-values

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

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

来源:R7RS report

【讨论】:

    【解决方案2】:

    只需使用let-values:

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

    上面会将两个结果提取到单独的变量中,你可以选择你需要的。

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 2020-11-20
      • 1970-01-01
      相关资源
      最近更新 更多