【问题标题】:Adding Overloaded Constructors to Implicit F# Type将重载的构造函数添加到隐式 F# 类型
【发布时间】:2011-03-06 18:37:33
【问题描述】:

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

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# 还很陌生,所以如果你能展示整个类型以及你所做的更改,我将不胜感激。

提前致谢,

鲍勃

附:如果您有任何其他建议可以使我的课程更具功能性,也请随时发表评论。

【问题讨论】:

    标签: f# constructor overloading implicit


    【解决方案1】:

    我可能会这样做:

    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 中还有一个matrix type。

    【讨论】:

    • 我注意到那里的 Matrix 类,但尝试使用它时遇到了困难,主要是因为我真的是 F# 新手。我正在将我理解的 C# 代码转换为 F# 代码以在大多数情况下学习 F#,然后我将再次尝试 Powerpack Matrix 类。感谢您的出色回答和快速响应。
    猜你喜欢
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2020-09-13
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    相关资源
    最近更新 更多