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

时间:2014-04-04 21:38:36

标签: julia

有一个带三个参数的函数。

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

另一个返回元组的函数。

g() = (1, 2, 3)

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

f(g()) # ERROR

2 个答案:

答案 0 :(得分:26)

使用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

答案 1 :(得分:4)

使用 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

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