Dearests,
today I found a disturbing (yet documented … ) behavior of julia. Let’s see:
struct T a::Vector{Int}; end
T(N) = T(zeros(Int,N))
Now aiming at a Vector
of initialized Ts I (mistakenly) did a
julia> x=fill(T(3),2)
2-element Array{T,1}:
T([0, 0, 0])
T([0, 0, 0])
The problem is that now the 2 elements in the vector are indeed the same:
julia> x[1].a[1] = 1;
julia> x
2-element Array{T,1}:
T([1, 0, 0])
T([1, 0, 0])
No big deal, a comprehension would have produced my intended result:
julia> y = [T(3) for i=1:2];
julia> y[1].a[1] = 1;
julia> y
2-element Array{T,1}:
T([1, 0, 0])
T([0, 0, 0])
hooray! the elements are now different. Of course, reading the docs is always a good idea: ?fill
“[…] If x is an object reference, all elements will refer to the same object. fill(Foo(), dims) will return an array filled with the result of evaluating
Foo() once.”
Now the two questions:
- What is the rationale behind having fill returning “all elements referring to the same object”
- What is the julian way to do what I wanted, beside the comprehension? For vectors comprehensions are ok but with arrays with more elaborated layouts it is a bit of a pain.
Cheers
Andrea