1
votes

I have several times used the expression anArray.[i] to access an element from an array.

but all the sudden when i try to make a very very simple function then i get an error.

let safeIndexIf anArray i =
  anArray.[i] 

I need to make a function that returns the ith element of the array so i thought that was an easy one but no...

The Error:

The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints

Why is this not working? I dont know what the error means by that. All i know i have done something similar to this lots of times to access an element of anArray so why can't i this time?

1

1 Answers

7
votes

It means the compilers type inference cannot determine that anArray is indeed an array.

The error message is suggesting you add a type annotation, you could do something like this to say that anArray is a generic array:

let safeIndexIf (anArray : array<'a>) i =
    anArray.[i]

If you want to avoid type annotations you could try rewriting your function to use Array.item which has the same behaviour:

let safeIndexIf anArray i =
    Array.item i anArray