简体   繁体   English

如何在F#中使用带有两个参数的int二维数组的函数

[英]How can I use function in F# with two parametes which are 2D arrays of ints

I am totally new in f# and i need help for my homework 我是f#的新手,需要作业帮助

i have this function and when i call it with parameters it returns an error 我有这个功能,当我用参数调用它返回一个错误

here is the code 这是代码

let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
    let result_row = (matrix1.GetLength 0)
    let result_column = (matrix2.GetLength 1)
    let ret = Array2D.create result_row result_column 0
    for x in 0 .. result_row - 1 do
        for y in 0 .. result_column - 1 do
            let mutable acc = 0
            for z in 0 .. (matrix1.GetLength 1) - 1 do
                acc <- acc + matrix1.[x,z] * matrix2.[z,y]
            ret.[x,y] <- acc
    ret

here is the error message: 这是错误消息:

error FS0001: Expecting a type supporting the operator '*' but given a tuple type 错误FS0001:期望支持运算符'*'但给定元组类型的类型

let mat3 = (MatrixMultiply (mat1, mat2))
printfn "%A" mat3

this is way i am using this function, mat1 and mat2 variables are 3x3 2D matrices 这就是我使用此函数的方式,mat1和mat2变量是3x3 2D矩阵

let mat1 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))
let mat2 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))

The problem is how you defined mat 1 and mat 2 : 问题是如何定义mat 1mat 2

let mat1 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))
let mat2 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))

The problem is that (rand.Next(x+10),rand.Next(y+10) is a tuple, (val1, val2) . mat1 and mat2 are 2D Arrays of tuples . If you just write it: 问题是(rand.Next(x+10),rand.Next(y+10)是一个元组, (val1, val2) mat1mat22D元组数组 。如果您只写它:

let mat1 = Array2D.init 3 3 (fun x y -> rand.Next(x + y)) // or whatever max number you want
let mat2 = Array2D.init 3 3 (fun x y -> rand.Next(x + y))
let mat3 = MatrixMultiply(mat1, mat2)

it will work. 它会工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM