# Flatten nested tuples to a tuple

I thought I would find a straightforward answer but haven’t been able to locate one. Sorry if this is a stupid question: What’s the simplest way to flatten a nested tuple?

The problems is, I call a function which returns a tuple of a different number of elements depending on the argument and I need to add one element in an intermediate function and return them together:

``````func(flag) = flag ? (2,3,4) : (2,3,4,5)

function myfunc()
a = 1
b, c, d = func(true) # When you know # of elems.
return (a, b, c, d) # Works
end

function myfunc2(flag)
a = 1
t = func(flag)
return vcat(a, collect(t))
end

function myfunc3(flag)
a = 1
t = func(flag)
return myflatten(a, t) # What function?
end

a, b, c, d = myfunc()
a, b, c, d = myfunc2(true)
a, b, c, d, e = myfunc3(false)
``````

In the above toy example, `myfunc3()` uses a fictitious function `myflatten()`, but is there a function like that?

`myfunc2()` works fine. It converts the tuple to a vector and returns the concatenated vector. So, this would be the simplest solution if there is no existing function to flatten tuples.

Simply splatting the tuple should be enough in your case:

``````julia> func(flag) = flag ? (2,3,4) : (2,3,4,5)
func (generic function with 1 method)

julia> a = 1
1

julia> t = func(true)
(2, 3, 4)

julia> (a, t...)
(1, 2, 3, 4)
``````
2 Likes

splatting

!!! That’s the word that I should have used to search the Internet. Thank you! After all, my question was stupid.