0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Julia1.9.2】fill()で嵌った話

Last updated at Posted at 2023-10-14

嵌まったこと

Julia1.9.2にて, fill()で作成した配列値を再代入したら, 代入された配列以外の配列の値も変わる.

具体的なコード

以下のようなコードを書いて, Julia1.9.2で実行した.

res = fill([0, 0], 10)
res[1][1] = 2

これを実行するとres は以下のようになる想定だ.

res[1] = [2, 0]
res[2] = [0, 0]
res[3] = [0, 0]
...

だが, 実際の実行結果は想定通りにならない.
実行した結果は, 実は以下のようになる.

res[1] = [2, 0]
res[2] = [2, 0] #なぜかこれも変わる
res[3] = [2, 0] #なぜかこれも変わる
...

想定とは違い, 他のインデックスの配列の値まで変わってしまう.
ちなみに, 以下のコードは想定通りに動く.

res = fill([0, 0], 10)
res[1] = [2, 0]

これの実行結果は,

res[1] = [2, 0]
res[2] = [0, 0]
res[3] = [0, 0]

原因

公式ドキュメントに記載があった.
これに依ると, fill()で作成された値そのものへの変更は, ほかのものにも跳ねるらしい.
わかるかそんなの.

対策

公式ドキュメントに書いてあったが, 内包表記を使いましょうとのことだった.
確かに下記のコードでは, 無事に想定通りの挙動になった.

a = [[0, 0] for _ in 1:10]
a[1][1] = 1
#= 実行結果
a[1] = [1, 0]
a[2] = [0, 0]
a[3] = [0, 0]
...
=#
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?