How to pass a two-dimensional array of a function in F #?

I am trying to create a function in F # that takes a two-dimensional array of integers (9 by 9) as input and subsequently prints its contents. The following code shows what I did:

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 output the type of the matrix, and this gives me the following error: "The operator 'expr. [Idx]' used an object of an undefined type based on the information before this program point. Consider adding additional type restrictions."

I tried using type annotation in the function definition, but I think I did it wrong. Any idea how I can overcome this problem?

+4
source share
2 answers

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 input algorithm works.

+6
source

The type inference algorithm does not like the parenthesis operator because it cannot guess which type the object is.

A workaround would be to give the matrix a function that the compiler knows, in this example Array2D.get does the same thing as the bracket operator. He knows this is an int matrix due to "% d" on printf

 let printMatrix matrix = for i in 0..8 do for j in 0..8 do printf "%d" <| Array2D.get matrix ij printf "\n" 
+1
source

Source: https://habr.com/ru/post/1479110/


All Articles