将c#结构体转换为f#

本文关键字:转换 结构体 | 更新日期: 2023-09-27 18:14:24

我在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实现为像我上面的代码一样的数组。

将c#结构体转换为f#

可以使用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

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