Structure Constructors

I have a simple structure with an array and an associate (fitness) value.

    mutable struct Solution
        genome::Array
        fitness
    end

I want to put in a zero’d constructor so I did the following and got “I get this error LoadError: MethodError: no method matching Main.Scratch.Solution{Int64}(::Int64)”.

mutable struct Solution{T}
        genome::Vector{T}
        fitness
        Solution(vector::Vector, fitness) = new{T}(vector, fitness)
        Solution(sz::Int64) = new{T}(zeros(T, sz), 0)
end

if I do the following I get ‘LoadError: UndefVarError: T not defined’;

mutable struct Solution{T}
        genome::Vector{T}
        fitness
        Solution{T}(vector::Vector, fitness) = new{T}(vector, fitness)
        Solution{T}(sz::Int64) = new{T}(zeros(T, sz), 0)
    end

I’m at a loss how to form these constructors properly.

The first constructor needs a where clause:

Solution(genome::Vector{T}, fitness) where T = new{T}(genome, fitness)

In the second constructor you need to provide the type information

Solution(::Type{T}, sz::Int) where T = new{T}(zeros(T, sz), 0)

Then you can call it like this (Wax is the name of my test module)

julia> Wax.Solution(Int, 7)
Main.Wax.Solution{Int64}([0, 0, 0, 0, 0, 0, 0], 0)

It also possible to provide a constructor with a default type (Float64):

mutable struct Solution{T}
    genome::Vector{T}
    fitness
    Solution(genome::Vector{T}, fitness) where T = new{T}(genome, fitness)
    Solution(::Type{T}, sz::Int) where T = new{T}(zeros(T, sz), 0)
    Solution(sz::Int) = Solution(Float64, sz)
end
2 Likes

Thanks! I’ll give it a try.