【问题标题】:how to pass tuple as function arguments如何将元组作为函数参数传递
【发布时间】:2014-04-05 06:26:59
【问题描述】:

得到一个接受三个参数的函数。

f(a, b, c) = # do stuff

还有一个返回元组的函数。

g() = (1, 2, 3)

如何将元组作为函数参数传递?

f(g()) # ERROR

【问题讨论】:

    标签: julia


    【解决方案1】:

    使用 Nanashi 的例子,线索是调用f(g())时的错误

    julia> g() = (1, 2, 3)
    g (generic function with 1 method)
    
    julia> f(a, b, c) = +(a, b, c)
    f (generic function with 1 method)
    
    julia> g()
    (1,2,3)
    
    julia> f(g())
    ERROR: no method f((Int64,Int64,Int64))
    

    这表明这会将元组(1, 2, 3) 作为f 的输入而无需解包。要解压,请使用省略号。

    julia> f(g()...)
    6
    

    Julia 手册中的相关部分在这里:http://julia.readthedocs.org/en/latest/manual/functions/#varargs-functions

    【讨论】:

    • 我更喜欢 f(g()...) 而不是 apply,我认为第一个在 Julia 中更惯用。
    • @AJcodez:是否可以将我的答案删除为已接受的答案并将其标记为答案?无论如何,我相信这会更好。
    • 文档似乎已移动。今天的链接是docs.julialang.org/en/stable/manual/functions/…
    【解决方案2】:

    使用apply

    julia> g() = (1,2,3)
    g (generic function with 1 method)
    
    julia> f(a,b,c) = +(a,b,c)
    f (generic function with 1 method)
    
    julia> apply(f,g())
    6
    

    如果这有帮助,请告诉我们。

    【讨论】:

      猜你喜欢
      • 2011-10-05
      • 2012-05-24
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多