Thanks for the suggestions! I think I will go with Steven G. Johnson's
solution and try to implement setindex! such as to be able to guarantee the
simplex constraints. Once that convenient getindex and setindex! methods
are implemented, I hope that nobody tries to mess with the fields directly.
In the end, complete immutability is rather a subordinate goal in my case.
However, I am still looking for a way to implement the constraints more
conveniently than writing all possible setindex! methods from scratch up,
especially since I ultimately would like my type to behave just identical
to a standard Array{Float64} (besides the constraints, of course). Hence,
what I am searching for is probably a way to inherit all methods from
Array{Float64}, only manipulating the setindex! methods, hopefully with
some type of metaprogramming.
For this, I think it is better to start a new threat, since I suppose it
should be a more general topic that probably more julia users could search
for.
On Tuesday, 31 December 2013 16:07:57 UTC+1, Steven G. Johnson wrote:
>
>
>
> On Tuesday, December 31, 2013 7:13:10 AM UTC-5, Christian Groll wrote:
>>
>> However, I do not get how I could extend this for the n-dimensional case.
>> Here, I thought that I would have to use one field which stores a
>> n-dimensional vector:
>>
>> immutable nDimSimplex
>> points::Vector{Float64}
>>
>> nDimSimplex(x::Vector{Float64}) = (abs(sum(x) - 1) > 1e-10) ?
>> error("entries must sum to one") : new(x)
>> end
>>
>> Now, I think that it will not be possible to change the vector that the
>> field points to. However, the entries of the vector itself still can be
>> changed without restrictions. Any recommendations?
>>
>
> You could simply tell users not to access simplex.points directly.
> Instead, override getindex/setindex! so that you can do simplex[i] for
> simplex <: nDimSimplex. Your setindex! method could enforce the invariants
> (e.g. dividing by sum(x) after every change to renormalize, and throwing an
> error for negative entries.)
>
> (I would also make nDimSimplex a subtype of AbstractVector{Float64}. For
> AbstractVector subtypes, you should normally provide methods for at least:
> size, getindex, setindex!, and similar.)
>