之前尝试过用C#来表达这些概念,但是遇到了语言障碍:语言不够丰富,或者不够具体。例如,如果我这样定义一个字段的元素:
public abstract class FieldElement
{
public abstract FieldElement Add(FieldElement another);
public abstract FieldElement SumInvert();
public abstract FieldElement MultiplicationInvert();
public abstract FieldElement MultiplyBy(FieldElement another);
public abstract FieldElement One; //Multiplication neutral element
public abstract FieldElement Zero; //Addition neutral element
public FieldElement Subtract(FieldElement another)
{
return this.Add(another.SumInvert());
}
public FieldElement Divide(FieldElement another)
{
return this.MultiplyBy(another.MultiplicationInvert());
}
public virtual FieldElement Power(uint b)
{
if (b == 0)
return this.One;
else
{
FieldElement result = this;
for (int i = 0; i < b - 1; i++)
result = result.MultiplyBy(result);
return result;
}
}
}
然后我像这样定义实数:
public class RealNumber : FieldElement
{
public double Value { get; set; }
public RealNumber(double value)
{
this.Value = value;
}
public override FieldElement Power(uint b)
{
return new RealNumber(Math.Pow(Value, b));
}
public override FieldElement Add(FieldElement another)
{
if (another.GetType() != typeof(RealNumber)) //Ugly typecast to enforce type-safety
throw new ArgumentException("RealNumber expected in Add method");
return new RealNumber(Value + (another as RealNumber).Value);
}
}
然后我可以定义对字段元素的一般操作(通过使用泛型):
public class FieldOperations<T> where T: FieldElement
{
public T Add(T a, T b)
{
return a.Add(b) as T;
}
public T Multiply(T a, T b)
{
return a.MultiplyBy(b) as T;
}
public T Subtract(T a, T b)
{
return a.Subtract(b) as T;
}
public T Divide(T a, T b)
{
return a.Divide(b) as T;
}
public T Power(T a, uint b)
{
return a.Power(b) as T;
}
}
我将在代码中这样使用它:
public class TestFieldOperations
{
public static void TestAddRealNumbers()
{
FieldOperations<RealNumber> operations = new FieldOperations<RealNumber>();
RealNumber a = new RealNumber(0.5);
RealNumber b = new RealNumber(0.7);
RealNumber c = operations.Add(a, b);
RealNumber d = operations.Power(c, 3);
}
}
同样,我可以在向量上使用 FieldOperations,在 InvMatrix 上使用 FieldOperations...
能够以类型安全和面向对象的方式抽象字段操作的概念可能非常强大:能够在同一抽象级别处理数字、向量和(可逆)矩阵算术。