I’m looking to defined types which have certain fields, such as a matrix, and that constructs that matrix according to certain rules at the moment of type definition. Thus the user need not give the matrix, as it will be filled anyways. The way I found to do it is the following, but it feels wrong; is there a cleaner way?
struct RandHaar <: Interferometer
m::Int
U::Matrix{ComplexF64}
RandHaar(m,U) = new(m,rand_haar(m)) #the “rand_haar” function gives a specific matrix (sampled according from the haar measure in this case)
end
RandHaar(n) = RandHaar(n, Matrix{ComplexF64}(undef,n,n))
If you don’t even want the user to have the option of providing the matrix than you can just replace the inner constructor with your function
struct RandHaar <: Interferometer
m::Int
U::Matrix{ComplexF64}
RandHaar(n) = new(n, Matrix{ComplexF64}(undef,n,n))
end
With this RandHaar(5)
will work as you expect and RandHaar(5,someMatrix)
will error
Sorry I wasn’t clear in my example : the “rand_haar” function gives a specific matrix (sampled according from the haar measure in this case), and I don’t see how to apply it with your solution?
Ah, I misunderstood your original code. It should then be as simple as making the inner constructor only a single argument and eliminating the outer constructor. (If I’m interpreting your desire correctly).
struct RandHaar <: Interferometer
m::Int
U::Matrix{ComplexF64}
RandHaar(m) = new(m,rand_haar(m))
end
Yes, this works, thanks a lot!