# a = [1, 2] と a[1], a[2] = 1, 2 の違い¶

2018-01-07

In [7]:
a = 0
b = Array{typeof(a),1}(2)
@show b
b[1] = a
@show b
a = 1
b[2] = a
@show b;

b = [152591088, 152591088]
b = [0, 152591088]
b = [0, 1]


In [8]:
a = [0,0]
b = Array{typeof(a),1}(2)
@show b
b[1] = a
@show b
a = [1, 2]
b[2] = a
@show b;

b = Array{Int64,1}[#undef, #undef]
b = Array{Int64,1}[[0, 0], #undef]
b = Array{Int64,1}[[0, 0], [1, 2]]


これも「意図した通り」だろう.

しかし, a = [1, 2]a[1], a[2] = 1, 2 に変えると次のようになってしまう.

In [9]:
a = [0,0]
b = Array{typeof(a),1}(2)
@show b
b[1] = a
@show b
a[1], a[2] = 1, 2
b[2] = a
@show b;

b = Array{Int64,1}[#undef, #undef]
b = Array{Int64,1}[[0, 0], #undef]
b = Array{Int64,1}[[1, 2], [1, 2]]


b の要素がどちらも [1, 2] になってしまった!

In [10]:
a = [0,0]
b = Array{typeof(a),1}(2)
@show b
b[1] = copy(a)
@show b
a[1], a[2] = 1, 2
b[2] = a
@show b;

b = Array{Int64,1}[#undef, #undef]
b = Array{Int64,1}[[0, 0], #undef]
b = Array{Int64,1}[[0, 0], [1, 2]]


さらに以下のように2次元配列を使っても「意図した通り」になる.

In [15]:
a = [0,0]
b = Array{eltype(a),2}(2,2)
display(b)
b[:,1] = a
display(b)
a[1], a[2] = 1, 2
b[:,2] = a
display(b);

2×2 Array{Int64,2}:
87998960  87361424
88668624  87366032
2×2 Array{Int64,2}:
0  87361424
0  87366032
2×2 Array{Int64,2}:
0  1
0  2