我使用隐式类型构造创建了以下类型:
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#很新,所以如果你能用你的变化显示整个类型,我会非常感激。
提前致谢,
鲍勃
P.S。如果您有任何其他建议让我的课程更具功能性,请随时对此发表评论。
答案 0 :(得分: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中还有一个matrix type。