On 13 October 2014 07:34,  <[email protected]> wrote:
>
> Just to be sure that I understand your advice: an immutable should not be
> used for an object with large arrays? Hence the need for a composite type?

The answer to "mutable or not" is more complicated than that and
depends on how you want your type to behave.  Remember that both
mutables and immutables are composite types.

Here is a simple example of an immutable.

    immutable I
        efficiency::Int
        weights::Vector{Float64}
    end
    I() = I(17, zeros(4711))
    i = I()

    # This works, `weights` is a reference to an array, the array itself
    #   can be mutated.
    i.weights[:] += rand(size(i.weights))
    # This, however, will not work as you are trying to change the reference
    #   to refer to a new array.
    i.weights = rand(size(i.weights))
    # This also does not work as `efficiency` is an immutable value,
    #   not a reference.
    i.efficiency = 4711

And the corresponding mutable variant.

    type M
        efficiency::Int
        weights::Vector{Float64}
    end
    M() = M(17, zeros(4711))
    m = M()

    # This works, we mutate the referenced array.
    m.weights[:] += rand(size(m.weights))
    # This also works, we now change the `weights` reference to a new array.
    m.weights = rand(size(m.weights))
    # This also also works, we update the value of `efficiency`.
    m.efficiency = 4711

What it really comes down to is how you expect your type to be used
and what you find convenient.  It seems to me that you are working on
some sort of modelling task and I tend to make my model objects
immutable and only mutate the arrays that they refer to.  However, in
your case you seem to want the efficiency value to be stored along
with the arrays, for this you would probably want a mutable rather
than immutable type.

    Pontus

Reply via email to