Array.create和不规则数组 [英] Array.create and jagged array

查看:145
本文介绍了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)

一切都将如预期:

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

打印:

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

您正在创建一个数组,其中每个元素是一个参考的在同一阵列的。这意味着使用改编变异值[0] 也发生突变的改编值[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 [0]&LT;方式&gt; 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天全站免登陆