F#在多维数组中写入值

时间:2017-10-29 18:14:16

标签: arrays f#

我正在尝试计算协方差矩阵

  

运算符'expr。[idx]'已用于不确定的对象   根据此计划点之前的信息进行输入。考虑添加   进一步的类型约束

let FirstSeq = {1.0..10.0} let SecondSeq = {20.0..30.0} let All = seq {yield (0,FirstSeq); yield (1,SecondSeq)} let cov(first:seq<float>)(second:seq<float>) = Seq.map2 (*) first second |> Seq.average |> fun x -> x - Seq.average first * Seq.average second let CreateCovMatrix(strangeList:seq<int * seq<float>>) = let Size = Seq.length strangeList let CovMatrix = Array2D.init Size Size let CalculateCovMatrix = for (a, i) in strangeList do for (b, j) in strangeList do CovMatrix.[a,b]=cov(i)(j) CalculateCovMatrix let result = CreateCovMatrix(All) printf "%A" result

如何解决这个问题及其原因?

{{1}}

2 个答案:

答案 0 :(得分:4)

函数Array2D.init有3个参数,你错过了最后一个参数,这是初始化函数。

您可以通过以下方式快速修复它:

let CovMatrix = Array2D.init Size Size (fun _ _ -> 0.)

然后你会发现下一个问题:可变引用的赋值是<-运算符,而不是=,用于比较和绑定。

所以你的功能看起来像这样:

let CreateCovMatrix(strangeList:seq<int * seq<float>>) = 
    let Size = Seq.length strangeList
    let CovMatrix = Array2D.init Size Size (fun _ _ -> 0.)
    let CalculateCovMatrix = 
        for (a, i) in strangeList do
            for (b, j) in strangeList do
                    CovMatrix.[a,b] <- cov(i)(j)
    CalculateCovMatrix

但是,不是指定忽略输入并始终返回零的函数,而是可以使用函数Array2D.zeroCreate

let CovMatrix = Array2D.zeroCreate Size Size

答案 1 :(得分:3)

这种数学运算是函数式编程的优势所在, 虽然你目前正处于命令式范式。古斯塔沃处理了你的警告,但即使如此,你的功能也无法达到预期的效果。混合功能和命令式概念CREATE TABLE PRODUCT ( PRODID NUMERIC(6), DESCRIP CHAR(30), CONSTRAINT PRODUCT_PRIMARY_KEY PRIMARY KEY (PRODID) ); 现在返回CreateCovMatrix

当务之急:

unit

正常运作:

let createCovMatrix(strangeList:seq<int * seq<float>>) = 
    let size = Seq.length strangeList
    let covMatrix = Array2D.zeroCreate size size
    for (a, i) in strangeList do
        for (b, j) in strangeList do
            covMatrix.[a,b]<-cov(i)(j)
    covMatrix

多功能:

let createCovMatrix strangeList = 
    strangeList 
    |> Seq.map (fun (a, i) -> Seq.map (fun (b, j) -> cov i j) strangeList)
    |> array2D