gTcV
gTcV

Reputation: 2504

Function of parameter type in type definition

Assume I want to store I vector together with its norm. I expected the corresponding type definition to be straightforward:

immutable VectorWithNorm1{Vec <: AbstractVector}
    vec::Vec
    norm::eltype(Vec)
end

However, this doesn't work as intended:

julia> fieldtype(VectorWithNorm1{Vector{Float64}},:norm)
Any

It seems I have to do

immutable VectorWithNorm2{Vec <: AbstractVector, Eltype}
    vec::Vec
    norm::Eltype
end

and rely on the user to not abuse the Eltype parameter. Is this correct?

PS: This is just a made-up example to illustrate the problem. It is not the actual problem I'm facing.

Upvotes: 3

Views: 86

Answers (1)

Scott Jones
Scott Jones

Reputation: 1750

Any calculations on a type parameter currently do not work (although I did discuss the issue with Jeff Bezanson at JuliaCon, and he seemed amenable to fixing it). The problem currently is that the expression for the type of norm gets evaluated when the parameterized type is defined, and gets called with a TypeVar, but it is not yet bound to a value, which is what you really need it to be called with, at the time that that parameter is actually bound to create a concrete type.

I've run into this a lot, where I want to do some calculation on the number of bits of a floating point type, i.e. to calculate and use the number of UInts needed to store a fp value of a particular precision, and use an NTuple{N,UInt} to hold the mantissa.

Upvotes: 2

Related Questions