2011-03-06 33 views
1

我一直在使用隱式類型結構創建了以下類型:添加重載的構造函數來隱F#類型

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#非常陌生,所以如果你可以用你的改變顯示整個類型,我將不勝感激。

由於提前,

鮑勃

附:如果您有任何其他建議可以讓我的課更具功能性風格,請隨時對此進行評論。

回答

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] 

BTW,還有在F#PowerPack中一個matrix type

+0

我注意到了那裏的Matrix類,但嘗試使用它很困難,主要是因爲我對F#非常陌生。我將我理解的C#代碼轉換爲F#代碼,以便大部分學習F#,然後再次嘗試Powerpack Matrix類。感謝您的出色答覆和快速響應。 – Beaker 2011-03-06 20:07:20