2011-11-14 141 views
5

我有這樣的代碼在C#:轉換C#結構,以F#

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

爲什麼你不使用F#中的C#結構?你到底有什麼問題?你有什麼嘗試?順便說一下,可變結構是邪惡的,除非真的必要,否則你不應該使用它們。 – svick

+0

它只是我的代碼中的一小塊,該結構在一個類中,並且該類具有使用struct作爲Array的方法。我嘗試將我的C#類轉換爲F#類。我在示例代碼中添加了更多代碼 –

回答

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 

當使用一成不變的結構,你將不能修改該結構的各個字段。您需要替換數組中的整個結構值。您通常可以將計算實現爲結構的成員(例如Foo),然後只需編寫arr.[0] <- arr.[0].Foo()來執行更新。

+0

我對你的代碼有所瞭解,但是當我想在我的代碼中實現它時,我仍然不明白。在我的代碼中,結構是在一個類中,而在C#中,我可以輕鬆地將結構實現爲一個數組。我無法更好地解釋這一點,因爲我的英語不好。如果你不介意,請看看這個鏈接:http://stackoverflow.com/questions/8126680/need-help-to-convert-my-homework-from-c-sharp-to-f –

+0

哦對不起,似乎我打破了規則,因此鏈接已關閉 –