Help defining a parametric type

parametric-types

#1

I want to define a mutable struct:

mutable struct W{T <: Real}
    a::T
    b::T
    c::T
    
    W(a, b, c) = begin
                # some checks on a, b, c
                new{T}(a, b, c)
    end
end

When I go to create an instance I get an error:

P = W(0.5, 0.5, 0.5)
UndefVarError: T not defined

What’s happening?


#2

You need a T type parameter on the constructor.


#3

Also, for this specific problem, there is no reason to define an inner constructor; the constructors provided by the language as default should work fine. See parametric constructors.


#4

Thanks, I didn’t include those tests on a, b, c in the comment of my code. I need to check that a, b, c are positive and less than one, otherwise throw an error:

if 0 < a < 1 && 0 < b < 1 && 0 < c < 1
    new{T}(a, b, c)
else
    error("a, b, c must be positive and less than 1")
end