Array.create 和锯齿状数组 [英] Array.create and jagged array

查看:20
本文介绍了Array.create 和锯齿状数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法理解这种行为的原因:

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")

打印:

[|2; 2|]
[|2; 2|]

https://dotnetfiddle.net/borMmO

如果我更换:

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

到:

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

一切都会按预期进行:

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")

打印:

[|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.

推荐答案

当你写:

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

您正在创建一个数组,其中每个元素都是对同一个数组的引用.这意味着使用 arr.[0] 改变一个值也会改变 arr.[1] 中的值 - 因为两个数组元素指向同一个可变数组.你最终得到:

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 |]

当你写作时:

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

arr 数组中的每个位置调用提供的函数,因此您最终会为每个元素使用不同的数组(因此 arr.[0] <>arr.[1]).你最终得到:

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 |]

这篇关于Array.create 和锯齿状数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆