6

I am trying to convert this C# code to F#:

double[,] matrix;

public Matrix(int rows, int cols)
    {
        this.matrix = new double[rows, cols];
    }

 public double this[int row, int col]
    {
        get
        {
            return this.matrix[row, col];
        }
        set
        {
            this.matrix[row, col] = value;
        }
    }

Basically my biggest problem is creating the indexer in F#. I couldn't find anything that I could apply in this situation anywhere on the web. I included a couple of other parts of the class in case incorporating the indexer into a Matrix type isn't obvious. So a good answer would include how to make a complete type out of the three pieces here, plus anything else that may be needed. Also, I am aware of the matrix type in the F# powerpack, however I am trying to learn F# by converting C# projects I understand into F#.

Thanks in advance,

Bob

porges
  • 28,750
  • 3
  • 83
  • 112
Beaker
  • 2,594
  • 5
  • 29
  • 52

1 Answers1

14

F# calls them "indexed properties"; here is the MSDN page. In F# they work slightly differently - each indexed property has a name.

However, there is a default one called "Item". So an implementation of your example would look like this:

member this.Item
  with get(x,y) = matrix.[(x,y)]
  and  set(x,y) value = matrix.[(x,y)] <- value

Then this is accessed via instance.[0,0]. If you have named it something other than "Item", you would access it with instance.Something[0,0].

porges
  • 28,750
  • 3
  • 83
  • 112
  • You definitely solved the hardest part of my question, so I'll mark it an an answer. But please feel free to create the whole type Matrix from what I have given above if you like. I'm going to go try and figure that part out on my own, but others might appreciate it for future reference. Thanks for such a quick answer! – Beaker Mar 04 '11 at 03:26
  • 3
    @Beaker : You haven't posted a whole type above, just a constructor and index property. – ildjarn Mar 04 '11 at 04:32
  • For anyone interested I asked a question that further expands on this question here: http://stackoverflow.com/questions/5206911/using-f-indexed-properties-in-a-type – Beaker Mar 05 '11 at 21:32
  • MS's index properties page wasn't clear enough. This answer cleared it up. I like the nice clean way #F handles the indexing. Implementing two dimensional indexing (on a flat array) in C++ is complicated. – annoying_squid Aug 01 '18 at 13:32