Array.create and jagged array

I can not understand the reason for this 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) 

in

 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 that the array is a reference type. But I want to understand why this is happening. Since I did not expect such results.

+5
source share
1 answer

When you write:

 let arr = Array.create 2 (Array.zeroCreate count) 

You create an array in which each element is a reference to the same array. This means changing the value with arr.[0] also changes the value in arr.[1] - because two elements of the array point to the same mutable array. You are getting:

 [| x ; x |] \ / [| 0; 0 |] 

When you write:

 let arr = Array.init 2 (fun _ -> Array.zeroCreate count) 

The provided function is called for each position in the arr array, and so you get a different array for each element (and therefore arr.[0] <> arr.[1] ). You are getting:

  [| x ; y |] / \ [| 0; 0 |] [| 0; 0 |] 
+9
source

Source: https://habr.com/ru/post/1238022/


All Articles