Unpacking tuples in function call

This is not a help request more of a pleasant observation. I was working with tuples and needed to create a function where the tuples would be unpacked and used separately, something like:

function myFun(x::Int64, y::Float64)
  println("Do something with x: $x")
  println("Do something else with y: $y")
end

# Call it like this:
tp = (42, 3.1459)
myFun(tp[1], tp[2])

Then I though I’d look really silly if I could have done something like this instead:

function myFun((x, y)::Tuple{Int64, Float64})
  println("Do something with x: $x")
  println("Do something else with y: $y")
end

# Then call it like this:
myFun(tp)

I tried it and it worked! That’s awesome!

3 Likes

Yup, it’s great! It’s also a pretty new feature (as of v0.7/1.0: https://github.com/JuliaLang/julia/blob/master/HISTORY.md#new-language-features-2)

1 Like

I was very excited by being able to dispatch on Tuple (and, in a very similar way, NamedTuple) types the same time I decompose them, but in practice it lead to poor coding style for me. YMMV.