我想将一些Java代码转换成F #,以生成围绕给定点的多维点网格。 我想出了这个:
let gridGenerator midpoint stepSize steps =
seq {
let n = Array.length midpoint
let direction = Array.create n -steps
let mutable lastIndex = n-1
while lastIndex>=0 do
let next = midpoint |> Array.mapi (fun i x -> x+ direction.[i]*stepSize)
while lastIndex>=0 && direction.[lastIndex]=steps do
direction.[lastIndex]<- (-steps)
lastIndex<-lastIndex-1;
if lastIndex>=0 then
direction.[lastIndex]<-direction.[lastIndex]+1;
lastIndex <- n-1;
yield next;
}
除了代码写得非常命令式(我会感激有关如何修复它的提示),我还遇到了编译错误:
如何解决此错误?如何使其更加函数化?Program.fs(18,15): error FS0407: 可变变量 'lastIndex' 的使用方式是无效的。可变变量不能被闭包捕获。考虑消除对变量的修改或使用通过'ref'和'!'进行堆分配的可变引用单元。
示例:对于中点
[|0.0,1.0|]
,步长0.5
和步数1
,我期望得到以下任意一种输出结果。seq{[|-0.5, 0.5|], [|-0.5, 1.0|], [|-0.5, 1.5|], [|0.0, 0.5|], [|0.0, 1.0|], [|0.0, 1.5|], [|0.5, 0.5|], [|0.5, 1.0|], [|0.5, 1.5|]}
请注意,这将被执行多次,因此性能至关重要。
ref
。 - svick