Can't understand the reason of such behavior:
let example count =
let arr = Array.create 2 (Array.zeroCreate count)
for i in [0..count - 1] do
arr.[0].[i] <- 1
arr.[1].[i] <- 2
arr
example 2 |> Array.iter(printfn "%A")
Print:
[|2; 2|]
[|2; 2|]
https://dotnetfiddle.net/borMmO
If I replace:
let arr = Array.create 2 (Array.zeroCreate count)
to:
let arr = Array.init 2 (fun _ -> Array.zeroCreate count)
Everything will work as expected:
let example count =
let arr = Array.init 2 (fun _ -> Array.zeroCreate count)
for i in [0..count - 1] do
arr.[0].[i] <- 1
arr.[1].[i] <- 2
arr
example 2 |> Array.iter(printfn "%A")
Print:
[|1; 1|]
[|2; 2|]
https://dotnetfiddle.net/uXmlbn
I think the reason is the fact that the array - a reference type. But I want to understand why this is happening. Since I didn't expect such results.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…