How do I get Julia to specialize to Vararg{Type}
?
The docs say:
As a heuristic, Julia avoids automatically specializing on argument type parameters in three specific cases:
Type
,Function
, andVararg
.
However, they say you can get around this for Vararg
, for arbitrary types with Vararg{Any,N} where N
:
julia> h_vararg(x::Vararg{Any, N}) where {N} = x
h_vararg (generic function with 1 method)
julia> Base.specializations(@which h_vararg(1f0, 1.0))
Base.MethodSpecializations(MethodInstance for h_vararg(::Float32, ::Float64))
Then they say you can specialize on Type
with Type{T} where T
:
julia> g_type(t::Type{T}) where T = t
g_type (generic function with 1 method)
julia> Base.specializations(@which g_type(Float32))
Base.MethodSpecializations(MethodInstance for g_type(::Type{Float32}))
But what about if I want to combine them? Let’s see:
julia> h2_vararg(x::Vararg{Any,N}) where {N} = x
h2_vararg (generic function with 1 method)
julia> Base.specializations(@which h2_vararg(Float32, Float64))
Base.MethodSpecializations(MethodInstance for h2_vararg(::Type, ::Type))
Nope, this doesn’t specialize because we didn’t do the Type{T} where T
trick. But how should we do that within a Vararg
? Maybe just this?
julia> h3_vararg(x::Vararg{Type,N}) where {N} = x
h3_vararg (generic function with 1 method)
julia> Base.specializations(@which h3_vararg(Float32, Float64))
Base.MethodSpecializations(MethodInstance for h3_vararg(::Type, ::Type))
Nope… So how do we actually force specialization here?
Related:
- This came up in some of the discussion on Proposed alias for union types. While I think for that particular case it wouldn’t make sense because you would blow up the number of methods, I was just curious how you would actually do this if you wanted to.
- Also: Force specialization on varargs when the arguments are not all of the same concrete type by @dilumaluthge