gpt4 book ai didi

c# - 将 C# 结构转换为 F#

转载 作者:太空狗 更新时间:2023-10-29 22:28:01 28 4
gpt4 key购买 nike

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

最佳答案

您可以使用 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()执行更新。

关于c# - 将 C# 结构转换为 F#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8122905/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com