【问题标题】:Can Scheme expand a list as arguments?Scheme 可以将列表扩展为参数吗?
【发布时间】:2013-06-11 02:39:36
【问题描述】:

考虑到我有一个程序(plus x y)witch 正好需要两个参数。现在我还有一个列表,其中包含两个对象,例如(list 1 2)。因此,如果有 any 神奇的方法可以将列表扩展为两个参数。我们有一个 dot notion 版本,但这 不是 我想要的。我只想扩展列表,让 Scheme 相信我传递了两个参数而不是列表。

希望这些 Ruby 代码有所帮助:

a = [1, 2]
def plus(x,y); x+y; end

plus(*a)
# See that a is an array and the plus method requires
# exactly two arguments, so we use a star operator to
# expand the a as arguments

【问题讨论】:

  • 请记住,您也可以使用 apply 进行 curry。例如。而不是 (apply map (cons list list-of-lists)) 你做 (apply map list list-of-lists)

标签: lisp scheme


【解决方案1】:
(apply your-procedure your-list)

【讨论】:

    【解决方案2】:

    这是 Scheme 的等效代码:

    (define (plus x y)
      (+ x y))
    
    (plus 1 2)
    => 3
    
    (define a (list 1 2))
    (apply plus a)
     => 3
    

    扩展列表并将其作为参数传递给过程的“神奇”方法是使用apply。阅读您的口译员的documentation 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2013-08-09
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多