1

我使用隐式类型构造创建了以下类型:

open System

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]

  //Properties

  ///The number of Rows in this Matrix.
  member this.Rows = rows

  ///The number of Columns in this Matrix.
  member this.Cols = cols

  ///Indexed Property for this matrix.
  member this.Item
    with get(x, y) = matrix.[x, y]
     and set(x, y) value = 
        this.Validate(x,y)
        matrix.[x, y] <- value

  //Methods
  /// Validate that the specified row and column are inside of the range of the matrix.
  member this.Validate(row, col) =
    if(row >= this.Rows || row < 0) then raise (new ArgumentOutOfRangeException("row is out of range"))
    if(col >= this.Cols || col < 0) then raise (new ArgumentOutOfRangeException("column is out of range"))

但是现在我需要将以下重载构造函数添加到此类型(此处为 C#):

public Matrix(int rows, int cols)
    {
        this.matrix = new double[rows, cols];
    }

我遇到的问题是,似乎隐式类型中的任何重载构造函数都必须有一个参数列表,它是第一个构造函数的子集。显然我要添加的构造函数不符合这个要求。有没有办法使用隐式类型构造来做到这一点?我应该以哪种方式做到这一点?我对 F# 还很陌生,所以如果你能用你的变化来展示整个类型,我将不胜感激。

提前致谢,

鲍勃

PS如果您有任何其他建议可以使我的课程更加实用,请随时发表评论。

4

1 回答 1

3

我可能会这样做:

type Matrix(sourceMatrix:double[,]) =
  let matrix = Array2D.copy sourceMatrix
  let rows = (matrix.GetUpperBound 0) + 1
  let cols = (matrix.GetUpperBound 1) + 1

  new(rows, cols) = Matrix( Array2D.zeroCreate rows cols )

除非我们谈论的是经常创建的非常大的数组(即复制空数组成为性能瓶颈)。

如果要模拟 C# 版本,则需要一个可以从两个构造函数访问的显式字段,如下所示:

type Matrix(rows,cols) as this =

  [<DefaultValue>]
  val mutable matrix : double[,]
  do this.matrix <- Array2D.zeroCreate rows cols

  new(source:double[,]) as this =
    let rows = source.GetUpperBound(0) + 1
    let cols = source.GetUpperBound(1) + 1
    Matrix(rows, cols)
    then
      for i in 0 .. rows - 1 do
        for j in 0 .. cols - 1 do
          this.matrix.[i,j] <- source.[i,j]

顺便说一句,F# PowerPack 中还有一个矩阵类型

于 2011-03-06T19:30:07.183 回答