Given a NTuple{N, T}
, I’d like to generate the collection of all sub-tuples that can be obtained by removing one element from the original tuple. This collection of sub-tuples can be represented as an NTuple{N, NTuple{N-1, T}}
, which I’d like to be the inferred return-type of the function.
Do you know of any way to do this in an efficient, type-stable way? The “best” I could come up with is this generated function, but I wondered whether there existed a simpler way to achieve this…
@generated function subtuples(t::NTuple{N, T}) where {N, T}
expr = Expr(:tuple)
expr.args = map(1:N) do i
Expr(:tuple, (:(t[$j]) for j in 1:N if i != j)...)
end
expr
end
julia> t = (1,2,3)
(1, 2, 3)
julia> typeof(subtuples(t))
Tuple{Tuple{Int64, Int64}, Tuple{Int64, Int64}, Tuple{Int64, Int64}}
julia> using Test; @inferred subtuples(t)
((2, 3), (1, 3), (1, 2))
julia> using BenchmarkTools; @btime subtuples($t)
1.540 ns (0 allocations: 0 bytes)
((2, 3), (1, 3), (1, 2))
PS: in my use-cases, N is typically 2 or 3