添加重载的构造函数来隐F#类型
问题描述:
我一直在使用隐式类型结构创建了以下类型:添加重载的构造函数来隐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#非常陌生,所以如果你可以用你的改变显示整个类型,我将不胜感激。
由于提前,
鲍勃
附:如果您有任何其他建议可以让我的课更具功能性风格,请随时对此进行评论。
答
我可能只是这样做:
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。
我注意到了那里的Matrix类,但尝试使用它很困难,主要是因为我对F#非常陌生。我将我理解的C#代码转换为F#代码,以便大部分学习F#,然后再次尝试Powerpack Matrix类。感谢您的出色答复和快速响应。 – Beaker 2011-03-06 20:07:20