Array.create and jagged array

后端 未结 1 1896
说谎
说谎 2020-12-21 06:11

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
             


        
相关标签:
1条回答
  • 2020-12-21 06:11

    When you write:

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

    You are creating an array where each element is a reference to the same array. This means that mutating a value using arr.[0] also mutates the value in arr.[1] - because the two array elements are pointing to the same mutable array. You end up with:

    [| 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'll end up with different array for each element (and so arr.[0] <> arr.[1]). You end up with:

         [| x ;  y |]
           /       \
    [| 0; 0 |]   [| 0; 0 |]
    
    0 讨论(0)
提交回复
热议问题