I read about that when deal with array we should use like myArray.[i]
, however, from my experience myArray[i]
compiles too.
However, when I want to write to an array in .Net (so it is mutable), this gives an error let myArray.[i] = 3
but let myArray[i] =3
works.
What is the best practice to deal with such thing?
Also, should I use Array.get
or use .[]
?
How do I set value to a jagged array e.g. let myArray.[i].[j] = 5
3 Answers 3
1) If you want to assign a value to an array cell, use the assignment operator <-
:
myArray.[i] <- 3
2) let myArray[i] = 3
compiles because the compiler understands it as myArray
function with a list as its argument and returns 3
. If you read the warning and the type signature, you will see you're doing it wrong.
3) Array.get
is a single call to .[]
. Array.get
is convenient in some cases for function composition and avoiding type annotation. For example you have
let mapFirst arrs = Array.map (fun arr -> Array.get arr 0) arrs
vs.
let mapFirst arrs = Array.map (fun (arr: _ []) -> arr.[0]) arrs
Neither of your approaches is correct. Assuming that you have some definitions like
let myArray = [| 1; 7; 15 |]
let i = 2
what you actually want is something like this:
myArray.[i] <- 3
When you write
let myArray[i] = 3
you are actually defining a function myArray, which takes an integer list and returns an integer. This is not what you want at all.
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).
let setJagged (a: 'T[][]) (i: int) (j: int) (v: 'T) = a.[i].[j] <- v
andlet set2D (a: 'T[,]) (i: int) (j: int) (v: 'T) = a.[i,j] <- v
.