Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Indexer in F#

Tags:

matrix

f#

indexer

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

like image 897
Beaker Avatar asked Mar 04 '11 03:03

Beaker


People also ask

What statement do you use to implement an indexer?

To declare an indexer for a class, you add a slightly different property with the this[] keyword and arguments of any type between the brackets. Properties return or set a specific data member, whereas indexers return or set a particular value from the object instance.

What are indexers used for?

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.

What's the meaning of indexer?

indexer (plural indexers) A person or program which creates indexes. (computing, programming, . NET) A special property of a class allowing objects of the class to be accessed by index as though they were arrays or hash tables.

CAN interface have indexers?

Like a class, Interface can have methods, properties, events, and indexers as its members.


1 Answers

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].

like image 74
porges Avatar answered Sep 23 '22 02:09

porges