Question

There are no builtin matrix functions in C#, but there are in the F# powerpack.

Rather than using a third party or open source C# library, I wonder about rolling my own in F#, and exposing the useful bits to C#.

Wondered if anybody has already thought of this, or tried it, and whether it's a good idea.

Should I expose it as a class, or a load of static functions?

Or should I create a C# wrapper class, and have that call down to F#? Or have the F# use the C# class as input and output?

Any thoughts?

Answer thanks to Hath below: you can use the F# library directly in C# (operators as well!):

using System;
using System.Text;
using Microsoft.FSharp.Math;

namespace CSharp
{
  class Program
  {
    static void Main(string[] args)
    {

        double[,] x = { { 1.0, 2.0 }, { 4.0, 5.0 } };
        double[,] y = { { 1.0, 2.0 }, { 7.0, 8.0 } };
        Matrix<double> m1 = MatrixModule.of_array2(x);
        Matrix<double> m2 = MatrixModule.of_array2(y);
        var mp = m1 * m2;

        var output = mp.ToArray2();
        Console.WriteLine(output.StringIt());

      Console.ReadKey();
    }
  }

  public static class Extensions
  {
    public static string StringIt(this double[,] array)
    {
      var sb = new StringBuilder();
      for (int r = 0; r < array.Length / array.Rank; r++)
      {
          for (int c = 0; c < array.Rank; c++)
          {
              if (c > 0) sb.Append("\t");
              sb.Append(array[r, c].ToString());
          }
          sb.AppendLine();
      }
      return sb.ToString();
    }
  }
}
Was it helpful?

Solution

can you not just reference the f# library you need in c# and use it directly?

I've done a similar thing to reference the FSharp.Core.dll to get at the

Microsoft.FSharp.Math.BigInt class.

So you can probably just reference the FSharp.PowerPack.dll to get at the

Microsoft.FSharp.Math.Matrix<A> class

OTHER TIPS

There are very good Matrix classes in the XNA Framework. I'd either reference that dll, or most likely use reflector and copy and paste the code into my own solution. I know it doesn't answer your question directly, but just another idea....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top