24

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

2 Answers 2

39

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

Sign up to request clarification or add additional context in comments.

3 Comments

I prefer f(g()...) over apply, and I think the first is more idiomatic in Julia.
@AJcodez: Is it possible to remove my answer as the accepted one and mark this one as the answer instead? I believe this is better anyway.
The docs seemed to have moved. Today's link is docs.julialang.org/en/stable/manual/functions/…
6

Answer outdated as of Julia version 0.4, released in 2015:

In modern versions of Julia, use the ... operator f(g()...).


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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.