将C#结构转换为F#

时间:2011-11-14 14:18:49

标签: c# f#

我在C#中有这样的代码:

namespace WumpusWorld
    {
        class PlayerAI
        {
            //struct that simulates a cell in the AI replication of World Grid
            struct cellCharacteristics
            {
                public int pitPercentage;
                public int wumpusPercentage;
                public bool isPit;
                public bool neighborsMarked;
                public int numTimesvisited;
            }

            private cellCharacteristics[,] AIGrid;                    //array that simulates World Grid for the AI
            private enum Move { Up, Down, Right, Left, Enter, Escape };   //enum that represents integers that trigger movement in WumpusWorldForm class
            Stack<int> returnPath;                                      //keeps track of each move of AI to trace its path back
            bool returntoBeg;                                           //flag that is triggered when AI finds gold
            int numRandomMoves;                                         //keeps track of the number of random moves that are done

            public PlayerAI()
            {
                AIGrid = new cellCharacteristics[5, 5];
                cellCharacteristics c;
                returntoBeg = false;
                returnPath = new Stack<int>();
                numRandomMoves = 0;

                for (int y = 0; y < 5; y++)
                {
                    for (int x = 0; x < 5; x++)
                    {
                        c = new cellCharacteristics();
                        c.isPit = false;
                        c.neighborsMarked = false;
                        c.numTimesvisited = 0;

                        AIGrid[x, y] = c;
                    }
                }
            }
        }
    }

我不知道如何将这个C#结构转换为F#,并将struct实现为一个数组,就像我上面的代码一样。

1 个答案:

答案 0 :(得分:10)

您可以使用struct关键字(如Stilgar所示)或使用Struct属性来定义结构,如下所示。我还添加了一个初始化结构的构造函数:

[<Struct>]
type CellCharacteristics =
  val mutable p : int
  val mutable w : int
  val mutable i : bool
  val mutable ne : bool
  val mutable nu : int

  new(_p,_w,_i,_ne,_nu) = 
    { p = _p; w = _w; i = _i; ne = _ne; nu = _nu }

// This is how you create an array of structures and mutate it
let arr = [| CellCharacteristics(1,2,true,false,3) |]
arr.[0].nu <- 42 // Fields are public by default

但是,通常不建议使用可变值类型。这会导致令人困惑的行为,而且代码很难推理。不仅在F#中,甚至在C#和.NET中都不鼓励这样做。在F#中,创建不可变结构也更容易:

// The fields of the strcuct are specified as part of the constructor
// and are stored in automatically created (private) fileds
[<Struct>]
type CellCharacteristics(p:int, w:int, i:bool, ne:bool, nu:int) =
  // Expose fields as properties with a getter
  member x.P = p
  member x.W = w
  member x.I = i
  member x.Ne = ne
  member x.Nu = nu

使用不可变结构时,您将无法修改结构的各个字段。您需要替换数组中的整个struct值。您通常可以将计算实现为结构的成员(比如说Foo),然后只需编写arr.[0] <- arr.[0].Foo()来执行更新。