Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About using F# to create a Matrix assembly usable from C#

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();
    }
  }
}
like image 354
Benjol Avatar asked Nov 07 '08 12:11

Benjol


1 Answers

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
like image 93
Hath Avatar answered Sep 22 '22 09:09

Hath