Inspecting the source code of ForwardDiff.jl) , we can found this function
@generated function single_seed(::Type{NTuple{N,V}}, ::Val{i}) where {N,V,i}
ex = Expr(:tuple, [ifelse(i === j, :(one(V)), :(zero(V))) for j in 1:N]...)
return :(NTuple($(ex)))
end
which returns tuples with variable length of zeros with just one at specified location i
What is benefits of using @generated
while it can be implemented as regular function, And get the results like
function single_seed_not_gen(::Type{NTuple{N,V}}, ::Val{i}) where {N,V,i}
return tuple([ifelse(i == j , one(V), zero(V)) for j in 1:N]...)
end
with results
julia> single_seed_not_gen(NTuple{10,Int} ,Val(4))
(0, 0, 0, 1, 0, 0, 0, 0, 0, 0)
julia> single_seed_not_gen(NTuple{20,Int} ,Val(4))
(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)