fill(anArray,2) behaviour

#1

I have doubts about the usefulness of fill(anArray,2). The use case for the current behaviour seems limited (who needs 2 copies of the same array in an array?) and the potential for being misleading is considerable (falsely assuming that these two arrays can be independently changed).

Still, I admit that there might be reasons of internal logic for this behaviour. If so, I suggest a careful documentation. (Yes…I fell into this trap today. )

Example:

X = fill(zeros(2),2)
X[1][1] = 99

gives

 X
2-element Array{Array{Float64,1},1}:
 [99.0, 0.0]
 [99.0, 0.0]
0 Likes

#2

I felt into this trap in the past as well. To get different arrays you can do:

[zeros(2) for i in 1:2]
1 Like

#3

The reason is simply that is is precisely the same as the behavior of

X[1] = y
X[2] = y

combined with the fact that julia does not implicitly copy things.

I agree that this can be confusing at first, but, to be fair, this exact issue is already specifically outlined in the documentation of fill(), so I’m not sure how much more documentation is really needed.

In a perfect world, I might have chosen a more descriptive name (would “repeat” be better?).

3 Likes

#4

[zeros(2) for i in 1:2]

Thanks. That is indeed the way to do it.

this exact issue is already specifically outlined in the documentation of fill() ,

I believe the documentation says If x is an object reference, all elements will refer to the same object. I must admit that this was not entirely easy for me to parse.

0 Likes

#5

If someone wants to improve that documentation, it would be helpful to give an example like the one in your original post here.

3 Likes

#6

Fair enough. I’ll read up on how to do that (no, I don’t know) and then give it a try.

0 Likes