Got a function that takes three arguments.
f(a, b, c) = # do stuff
And another function that returns a tuple.
g() = (1, 2, 3)
How do I pass the tuple as function arguments?
f(g()) # ERROR
In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.
A tuple can be an argument, but only one - it's just a variable of type tuple . In short, functions are built in such a way that they take an arbitrary number of arguments. The * and ** operators are able to unpack tuples/lists/dicts into arguments on one end, and pack them on the other end.
If a method accepts a tuple as an argument, that means it accepts multiple values. If a method returns a tuple, that means it returns multiple values. As an example, the Invoke() method in BindableFunction accepts a tuple as an argument, meaning it can accept multiple arguments.
To expand tuples into arguments with Python, we can use the * operator. to unpack the tuple (1, 2, 3) with * as the arguments of add . Therefore, a is 1, b is 2, and c is 3. And res is 6.
Using Nanashi's example, the clue is the error when you call 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))
This indicates that this gives the tuple (1, 2, 3)
as the input to f
without unpacking it. To unpack it use an ellipsis.
julia> f(g()...) 6
The relevant section in the Julia manual is here: http://julia.readthedocs.org/en/latest/manual/functions/#varargs-functions
Use 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
Let us know if this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With