Yabert Yanuar
Yabert Yanuar

Reputation: 1027

can I define struct in a class in F#?

this is example code in C# :

class exampleClass
{
    struct exampleStruct
    {
        public int number;
    }

    private exampleStruct[,] e;                    
    private enum exampleMove { Up, Down, Right, Left, Enter, Escape };
    Stack<int> returnPath;
    bool returntoBeg;
    int numRandomMoves;

    public exampleClass()
    {
        e = new exampleStruct[5, 5];
        exampleStruct ex;
        returntoBeg = false;
        returnPath = new Stack<int>();
        numRandomMoves = 0;

        for (int y = 0; y < 5; y++)
        {
            for (int x = 0; x < 5; x++)
            {
                ex = new exampleStruct();
                ex.number = 0

                e[x, y] = ex;
            }
        }
    }
}

I have an example code like above, i want to translate it into F#. But the problem is, when i make a class using F# and define struct in it, it shows errors and pointing that i can't declare type inside class type. Any help?

Upvotes: 0

Views: 196

Answers (2)

Daniel
Daniel

Reputation: 47904

I think the following is a good workaround for nested types.

namespace MyNamespace

module private PrivateTypes =
  [<Struct>]
  type ExampleStruct(number: int) =
    member __.Number = number

open PrivateTypes

type ExampleClass() =
  let e = Array2D.init 5 5 (fun y x -> ExampleStruct(0))
  //other members

ExampleStruct is nested under PrivateTypes, which is only visible in the same file.

Upvotes: 2

kkm mistrusts SE
kkm mistrusts SE

Reputation: 5510

While you cannot nest types, you can use intrinsic complex types that F# provides. Tuples are often a good data structure for data that has not very wide, observable scope, such as it is in your case.

In practice, I usually define implementation types in a module called e. g. Internal, and do not allow them to escape from the library. You may also define separate module per logical group of classes or even per complex class implementation.

Upvotes: 1

Related Questions