Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 946
John Avatar asked Mar 24 '23 02:03

John


1 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 infrence algorithm works

like image 141
John Palmer Avatar answered Apr 01 '23 05:04

John Palmer