fork(2) download
  1. using System;
  2. using System.Text;
  3.  
  4. public struct Magma<T>
  5. {
  6. public readonly Func<T, T, T> op;
  7. public Magma(Func<T, T, T> op)
  8. {
  9. this.op = op;
  10. }
  11. }
  12.  
  13. public static class Magma
  14. {
  15. public static readonly Magma<float> FloatSum =
  16. new Magma<float>((a, b) => a + b);
  17. public static readonly Magma<int> IntSum =
  18. new Magma<int>((a, b) => a + b);
  19. }
  20.  
  21. public struct Matrix<T>
  22. {
  23. public readonly T[] Elems;
  24. public readonly int Dim;
  25.  
  26. public Matrix(int dim)
  27. {
  28. Dim = dim;
  29. Elems = new T[dim * dim];
  30. }
  31.  
  32. public Matrix(T[] elems)
  33. {
  34. Dim = (int)Math.Sqrt(elems.Length);
  35. Elems = elems;
  36. }
  37.  
  38. public override string ToString()
  39. {
  40. var sb = new StringBuilder();
  41. for (int i = 0; i < Dim; ++i)
  42. {
  43. for (int j = 0; j < Dim; ++j)
  44. sb.Append(Elems[i*Dim + j]).Append(' ');
  45. sb.AppendLine();
  46. }
  47. return sb.ToString();
  48. }
  49. }
  50.  
  51. public static class Matrix
  52. {
  53. public static Matrix<T> Sum<T>(Matrix<T> lhs, Matrix<T> rhs, Magma<T> sum)
  54. {
  55. var result = new Matrix<T>(lhs.Dim);
  56. for (int i = 0; i < lhs.Elems.Length; ++i)
  57. {
  58. result.Elems[i] = sum.op(lhs.Elems[i], rhs.Elems[i]);
  59. }
  60. return result;
  61. }
  62. }
  63.  
  64. public class Test
  65. {
  66. public static void Main()
  67. {
  68. var a = new Matrix<float>(new float[] { 1.1f, 2.2f, 3.3f, 4.4f });
  69. Console.WriteLine(Matrix.Sum(a, a, Magma.FloatSum));
  70. var b = new Matrix<int>(new int[] { 3, 5, 4, 9 });
  71. Console.WriteLine(Matrix.Sum(b, b, Magma.IntSum));
  72. }
  73. }
Success #stdin #stdout 0.04s 24000KB
stdin
Standard input is empty
stdout
2.2 4.4 
6.6 8.8 

6 10 
8 18