Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass tuple as function arguments

Tags:

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 
like image 779
AJcodez Avatar asked Apr 04 '14 21:04

AJcodez


People also ask

Can I pass a tuple as argument in Python?

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.

Can a function take a tuple as an argument?

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.

What is a tuple argument?

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.

How do you pass multiple tuples as parameters in Python?

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.


2 Answers

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

like image 74
Guillermo Garza Avatar answered Oct 01 '22 16:10

Guillermo Garza


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.

like image 32
NullDev Avatar answered Oct 01 '22 16:10

NullDev