Is it possible to generalize such function to arbitrary tuple size? I couldn't fin

Is it possible to generalize such function to arbitrary tuple size? I couldn’t find relevant information in docs.

function from_vec(::Type{MyType{Tuple{T1, T2}}}, x) where {T1, T2}
	MyType((f(T1, x), f(T2, x)))
end

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

Presumably, you do not intend to use this with “arbitrary” tuple size. If you are expecting to need this with more than 5ish parameters (and probably more than 3 for most situations) – there is almost certainly a better approach. Defining each case is not much of a bother, and likely cleanest. Even if there were 8 parameters, this is still a good way to go.

function from_vec(::Type{MyType{Tuple{T1}}}, x) where {T1}
	MyType((f(T1, x),))
end
function from_vec(::Type{MyType{Tuple{T1, T2}}}, x) where {T1, T2}
	MyType((f(T1, x), f(T2, x)))
end
function from_vec(::Type{MyType{Tuple{T1, T2, T3}}}, x) where {T1, T2, T3}
	MyType((f(T1, x), f(T2, x), f(T3, x)))
end
# ...
1 Like

There is also a trick to get this using tuple_type_head and tuple_type_tail from Base. I’m not sure how recommended it is, but it allows to do inferrable recursive definitions with tuple types. I’m removing MyType for simplicity.

julia> from_vec(::Type{Tuple{}}, x) = ()
from_vec (generic function with 1 methods)

julia> function from_vec(::Type{T}, x) where {T<:Tuple}
           S = Base.tuple_type_head(T)
           T1 = Base.tuple_type_tail(T)
           return (f(S, x), from_vec(T1, x)...)
       end
from_vec (generic function with 2 methods)

Then, for example,

julia> f(S, x) = S(x)
f (generic function with 1 method)

julia> from_vec(Tuple{Int, Float64}, 1)
(1, 1.0)
3 Likes