How to call parametric constructor appropriately in Julia?

Viewed 87

I wanted to call the constructor of composite type WeightedPool1D but I tried both WeightedPool1D(mask) and WeightedPool1D{Float64}(mask) but it did not work.

Thanks!

Julia version: 1.6.1

My code:

# creating composite type
struct WeightedPool1D{T}
    n::Int
    c::Int
    mask::Matrix{Bool}
    weight::Matrix{T}
    function WeightedPool1D(mask::Matrix{Bool}) where T
        c, n = size(mask)
        weight = randn(T, c, n) / n
        new{T}(n, c, mask, weight)
    end
end

# create argument
mask = zeros(Bool, 3, 3)

Calling w = WeightedPool1D(mask) gives the error

julia> w = WeightedPool1D(mask)
ERROR: UndefVarError: T not defined

Calling w = WeightedPool1D{Float64}(mask) gives the error

julia> w = WeightedPool1D{Float64}(mask)
ERROR: MethodError: no method matching WeightedPool1D{Float64}(::Matrix{Bool})
1 Answers

The problem here is the inner constructor. There is nothing (from the input to the constructor) that defines what T should be.

If you want a default value of T, say Float64, you can define the following inner constructors

struct WeightedPool1D{T}
    n::Int
    c::Int
    mask::Matrix{Bool}
    weight::Matrix{T}

    # General constructor for any T, call as WeightedPool1D{Float64}(...)
    function WeightedPool1D{T}(mask::Matrix{Bool}) where T
        c, n = size(mask)
        weight = randn(T, c, n) / n
        new{T}(n, c, mask, weight)
    end
   
    # Construtors that defines a default T, call as WeightedPool1D(...)
    function WeightedPool1D(mask::Matrix{Bool})
        return WeightedPool1D{Float64}(mask) # Calls the other constructor, now with T = Int
    end
end

Example calls:

mask = zeros(Bool, 3, 3)

WeightedPool1D(mask)
WeightedPool1D{Float32}(mask)
Related