嘿夥計們,我從C++有以下一段代碼。C++到F#平滑翻譯
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等價。
我認爲你的第一個解決方案很有趣。 「讓我覺得」開箱即用「這裏可能不需要100%的不可變性,因爲無論如何董事會有可能變化,我只是希望避免(x,y)的可變性, – user627943 2011-03-23 03:45:49