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 に答える