0

我读到了在处理数组时我们应该使用 like myArray.[i],但是,根据我的经验,它myArray[i]也可以编译。

但是,当我想写入 .Net 中的数组时(因此它是可变的),这会产生错误 let myArray.[i] = 3let myArray[i] =3可以工作。

处理这种事情的最佳做法是什么?

另外,我应该使用Array.get还是使用.[]

如何将值设置为锯齿状数组,例如let myArray.[i].[j] = 5

4

3 回答 3

5

1) 如果要为数组单元赋值,请使用赋值运算符<-

myArray.[i] <- 3 

2)let myArray[i] = 3编译是因为编译器将其理解为myArray以列表为参数的函数并返回3. 如果您阅读警告和类型签名,您会发现自己做错了。

3)Array.get.[]. Array.get在某些情况下便于函数组合和避免类型注释。例如你有

let mapFirst arrs = Array.map (fun arr -> Array.get arr 0) arrs 

对比

let mapFirst arrs = Array.map (fun (arr: _ []) -> arr.[0]) arrs
于 2012-09-06T16:56:52.750 回答
4

您的两种方法都不正确。假设您有一些定义,例如

let myArray = [| 1; 7; 15 |]
let i = 2

你真正想要的是这样的:

myArray.[i] <- 3

当你写

let myArray[i] = 3

您实际上是在定义一个函数myArray,它接受一个整数列表并返回一个整数。这根本不是你想要的。

于 2012-09-06T16:56:27.997 回答
2

The problem here is that you're trying to embed an array assignment inside of a let expression. The expression let myArray[3] = 2 is not an assignment into an array. Rather, it's a function definition. See what happens in fsi:

let myArray[i] = 3;;
val myArray : int list -> int

(There's actually a warning in there as well). Formatting it differently also reveals this fact: let myArray [3] = 2.

As the others have pointed out, .[] is for array access, and to assign to an array, you use myArray.[i] <- 3 (not inside a let expression).

于 2012-09-06T17:03:56.747 回答