0

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

pad
41.3k7 gold badges94 silver badges168 bronze badges
asked Sep 6, 2012 at 16:48
1
  • let setJagged (a: 'T[][]) (i: int) (j: int) (v: 'T) = a.[i].[j] <- v and let set2D (a: 'T[,]) (i: int) (j: int) (v: 'T) = a.[i,j] <- v. Commented Sep 9, 2012 at 12:09

3 Answers 3

5

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
answered Sep 6, 2012 at 16:56
4

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.

answered Sep 6, 2012 at 16:56
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).

answered Sep 6, 2012 at 17:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.