using System; using System.Text; public struct Magma { public readonly Func op; public Magma(Func op) { this.op = op; } } public static class Magma { public static readonly Magma FloatSum = new Magma((a, b) => a + b); public static readonly Magma IntSum = new Magma((a, b) => a + b); } public struct Matrix { public readonly T[] Elems; public readonly int Dim; public Matrix(int dim) { Dim = dim; Elems = new T[dim * dim]; } public Matrix(T[] elems) { Dim = (int)Math.Sqrt(elems.Length); Elems = elems; } public override string ToString() { var sb = new StringBuilder(); for (int i = 0; i < Dim; ++i) { for (int j = 0; j < Dim; ++j) sb.Append(Elems[i*Dim + j]).Append(' '); sb.AppendLine(); } return sb.ToString(); } } public static class Matrix { public static Matrix Sum(Matrix lhs, Matrix rhs, Magma sum) { var result = new Matrix(lhs.Dim); for (int i = 0; i < lhs.Elems.Length; ++i) { result.Elems[i] = sum.op(lhs.Elems[i], rhs.Elems[i]); } return result; } } public class Test { public static void Main() { var a = new Matrix(new float[] { 1.1f, 2.2f, 3.3f, 4.4f }); Console.WriteLine(Matrix.Sum(a, a, Magma.FloatSum)); var b = new Matrix(new int[] { 3, 5, 4, 9 }); Console.WriteLine(Matrix.Sum(b, b, Magma.IntSum)); } }