嘿伙计们,我有以下来自 C++ 的代码。
for (int i=0; i < nObstacles; i++)
{
int x,y;
bool bAlreadyExists;
do {
x = rand() % nGridWidth;
y = rand() % nGridHeight;
} while (HasObstacle(x, y));
SetObstacle(x, y, true);
}
我可以直接将它翻译成 F# 没有问题。
let R = new System.Random()
for i=0 to nObstacles do
let mutable bGoodToGo = false;
let mutable x =0;
let mutable y = 0
while not bGoodToGo do
x <-R.Next(nWidth)
y <-R.Next(nHeight)
bGoodToGo <- IsEmptyAt x y
board.[x,y]<-Obstacle;
当然,这可能会让你们中的大多数人感到畏缩,因为这不是 F# 的本意。这段代码有一些 F# 的“unkosher”概念,例如 do-while 循环和可变数据。
但我有兴趣看到的是具有不可变数据的“正确”F# 翻译,以及某种等效的 do-while。