Tuple constructor forgets types

According to the documentation it seems to be a totally valid and even encouraged application to improve typeperformance by storing Type{T} types:

https://docs.julialang.org/en/v1/manual/types/#man-typet-type

Another important use case for Type is sharpening field types which would otherwise be captured less precisely, e.g. as DataType in the example below where the default constuctor could lead to performance problems in code relying on the precise wrapped type (similarly to abstract type parameters).

julia> struct WrapType{T}
       value::T
       end

julia> WrapType(Float64) # default constructor, note DataType
WrapType{DataType}(Float64)

julia> WrapType(::Type{T}) where T = WrapType{Type{T}}(T)
WrapType

julia> WrapType(Float64) # sharpened constructor, note more precise Type{Float64}
WrapType{Type{Float64}}(Float64)

In your particular case, you can just use Core.Typeof instead of typeof.

I tried it, I even constructed Type{...} values explicitly, but it didn’t works as reported in the top question.

Do you have a way it works for you? How do you construct a Tuple which uses Core.Typeof instead of typeof?

Not really, it’s just that types are mainly for dispatch in Julia, which is usually done by the compiler, not the user, so the type system was not designed for a lot of introspection and manipulation of the kind you are looking for.

Again, it is hard to respond to this without concrete code, but generally note that the compiler employs heuristics to give up on type inference in some cases, otherwise compilation times would be excessive.

These heuristics are not part of the language definition and may change without being considered breaking. This is the key point here: with Julia, you are not getting a full ontology of higher-order types, at least not in practice. If you insist on doing it, you will encounter examples which just broaden type or give up inference unexpectedly, despite fact that it “should” work. You can keep going a bit further with internals and various fixes, but it is an uphill struggle.

Unfortunately, even this meta-aspect of the language is not documented.

Perhaps that section of the manual should be rewritten or removed. Personally I think that all cases of Type{T} escaping method signatures lead to unexpected or surprising results sooner or later, so they should not be encouraged, and actively discouraged instead.

2 Likes