13
得到一個帶三個參數的函數。如何傳遞元組作爲函數參數
f(a, b, c) = # do stuff
而另一個函數返回一個元組。
g() = (1, 2, 3)
如何傳遞元組作爲函數參數?
f(g()) # ERROR
得到一個帶三個參數的函數。如何傳遞元組作爲函數參數
f(a, b, c) = # do stuff
而另一個函數返回一個元組。
g() = (1, 2, 3)
如何傳遞元組作爲函數參數?
f(g()) # ERROR
使用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
在朱莉婭手冊中的相關部分是在這裏:http://julia.readthedocs.org/en/latest/manual/functions/#varargs-functions
使用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
讓我們知道這是否有幫助。
不知道元組可以splatted,謝謝! – AJcodez
我更喜歡'f(g()...)'over'apply',我認爲第一個在Julia中比較習慣。 –
@AJcodez:是否可以將我的答案作爲已接受的答案移除,並將其標記爲答案?無論如何,我相信這是更好的。 – Manhattan