4

I am trying to create a function in F# that takes as input a two dimensional array of integers (9 by 9), and prints its content afterwards. The following code shows what I have done :

let printMatrix matrix=
    for i in 0 .. 8 do
        for j in 0 .. 8 do
            printf "%d " matrix.[i,j]
        printf "\n"

The problem is that F# does not automatically infer the type of the matrix, and it gives me the following error: "The operator 'expr.[idx]' has been used an object of indeterminate type based on information prior to this program point. Consider adding further type constraints".

I tried to use type annotation in the definition of the function, but I think I did it wrong. Any idea how I can overcome this issue?

John
  • 627
  • 10
  • 18

2 Answers2

6

Change it to

let printMatrix (matrix:int [,])=
    for i in 0 .. 8 do
        for j in 0 .. 8 do
            printf "%d " matrix.[i,j]
        printf "\n"

This is due to how the F# type infrence algorithm works

John Palmer
  • 25,356
  • 3
  • 48
  • 67
1

The type inference algorithm doesn't really likes the bracket operator, because it can't guess which type is the object.

A workaround would be to give the matrix to a function that the compiler knows the type, in that example, Array2D.get does the same thing as the bracket operator. It knows it's an int matrix because of the "%d" on the printf

let printMatrix matrix =
    for i in 0..8 do
        for j in 0..8 do
            printf "%d" <| Array2D.get matrix i j 
        printf "\n"
Bruno
  • 623
  • 2
  • 9
  • 24