在类型中使用F#索引属性

Bea*_*ker 1 f# types indexed-properties

我正在尝试将以下C#转换为F#:

    public class Matrix
    {
       double[,] matrix;

public int Cols
        {
            get
            {
                return this.matrix.GetUpperBound(1) + 1;
            }
        }

public int Rows
        {
            get
            {
                return this.matrix.GetUpperBound(0) + 1;
            }
        }

       public Matrix(double[,] sourceMatrix)
       {
        this.matrix = new double[sourceMatrix.GetUpperBound(0) + 1, sourceMatrix.GetUpperBound(1) + 1];
        for (int r = 0; r < this.Rows; r++)
        {
            for (int c = 0; c < this.Cols; c++)
            {
                this[r, c] = sourceMatrix[r, c];
            }
        }
       }

       public double this[int row, int col]
       {
         get
         {
             return this.matrix[row, col];
         }
         set
         {
             this.matrix[row, col] = value;
         }
       }
     }
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

type Matrix(sourceMatrix:double[,]) =
let mutable (matrix:double[,]) = Array2D.create (sourceMatrix.GetUpperBound(0) + 1) (sourceMatrix.GetUpperBound(1) + 1) 0.0
member this.Item
    with get(x, y) = matrix.[(x, y)]
    and set(x, y) value = matrix.[(x, y)] <- value
do
    for i = 0 to matrix.[i].Length - 1 do
    for j = (i + 1) to matrix.[j].Length - 1 do
        this.[i].[j] = matrix.[i].[j]
Run Code Online (Sandbox Code Playgroud)

我上面的类型似乎有两个问题,我不知道如何解决.第一个是矩阵.[(x,y)]预期类型为'a []但类型为double [,].第二个类型定义必须在成员和接口定义之前具有let/do绑定.问题是我正在尝试填充do块中的索引属性,这意味着我必须先创建它.

提前致谢,

短发

kvb*_*kvb 6

关于你的第一个问题,你要使用matrix.[x,y]而不是matrix.[(x,y)]- 你的矩阵由两个整数索引,而不是整数元组(尽管这些在概念上是相似的).

这里大致相当于你的C#:

type Matrix(sourceMatrix:double[,]) =
  let rows = sourceMatrix.GetUpperBound(0) + 1
  let cols = sourceMatrix.GetUpperBound(1) + 1
  let matrix = Array2D.zeroCreate<double> rows cols
  do
    for i in 0 .. rows - 1 do
    for j in 0 .. cols - 1 do
      matrix.[i,j] <- sourceMatrix.[i,j]
  member this.Rows = rows
  member this.Cols = cols
  member this.Item
    with get(x, y) = matrix.[x, y]
     and set(x, y) value = matrix.[x, y] <- value
Run Code Online (Sandbox Code Playgroud)

这假设您的矩阵实际上不能被重新分配(例如,在您发布的C#中,您可以创建您的matrix字段readonly- 除非您隐藏了其他代码).因此,行数和列数可以在构造函数中计算一次,因为矩阵的条目可能会更改,但其大小不会更改.

但是,如果您希望对代码进行更直接的翻译,则可以为新构造的实例指定名称(this在本例中):

type Matrix(sourceMatrix:double[,]) as this =
  let mutable matrix = Array2D.zeroCreate<double> (sourceMatrix.GetUpperBound(0) + 1) (sourceMatrix.GetUpperBound(1) + 1)
  do
    for i in 0 .. this.Rows - 1 do
    for j in 0 .. this.Cols - 1 do
      this.[i,j] <- sourceMatrix.[i,j]
  member this.Rows = matrix.GetUpperBound(0) + 1
  member this.Cols = matrix.GetUpperBound(1) + 1
  member this.Item
    with get(x, y) = matrix.[x, y]
     and set(x, y) value = matrix.[x, y] <- value
Run Code Online (Sandbox Code Playgroud)