F# F中闭包中的可变变量#
我正在尝试移植一些java Dof#格式的代码,它围绕给定点生成一个多维点网格。我想到了这个:F# F中闭包中的可变变量#,f#,F#,我正在尝试移植一些java Dof#格式的代码,它围绕给定点生成一个多维点网格。我想到了这个: let gridGenerator midpoint stepSize steps = seq { let n = Array.length midpoint let direction = Array.create n -steps let mutable lastIndex = n-1 while lastIndex>
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;
}
还请注意,这将执行多次,因此性能至关重要。让gridGenerator以中点步长为步长=
let gridGenerator midpoint stepSize steps =
seq {
let n = Array.length midpoint
let direction = Array.create n -steps
let lastIndex = ref (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
decr lastIndex
if !lastIndex >= 0 then
direction.[!lastIndex] <- direction.[!lastIndex] + 1
lastIndex := n - 1
yield next
}
序号{
设n=Array.length中点
让方向=数组。创建n个步骤
设lastIndex=ref(n-1)
而!lastIndex>=0 do
让next=midpoint |>Array.mapi(乐趣x->x+方向。[i]*步长)
而!lastIndex>=0&&direction。[!lastIndex]=步骤执行
方向。[!lastIndex]=0,然后
方向。[!lastIndex]以下是一种更实用的方法:
let rec gridGenerator midpoint stepSize steps =
match midpoint with
| [] -> Seq.singleton []
| p::point ->
seq {
for d in - stepSize * steps .. stepSize .. stepSize * steps do
for q in gridGenerator point stepSize steps do
yield (p + d) :: q
}
签名如下:
val gridGenerator : int list -> int -> int -> seq<int list>
val gridGenerator:int list->int->int->seq
如果重复使用结果,请记住将其缓存或转换(到数组或列表)。现在您可以只使用F#4,它没有这种约束。闭包无法捕获可变变量严重的设计,ftf。错误信息告诉你做什么:使用.@ LePeP-这避免了C++中可能发生的一类微妙的错误。例如,@ LePeple如果你不需要手握,为什么不在C++中编码?更好的是在汇编中编码——在那里没有手持。@ LePee,请参阅设计原理。所以<代码> REF只是一个盒子。(在函数术语中)?编译。但为什么它到处都有int类型?我认为F#应该能够泛化类型,而不是猜测int?0和1的类型是int
,而且默认的decr
函数只适用于int
。我还认为数组索引必须是整数(一个.NET framework设计中的错误)。
val gridGenerator : int list -> int -> int -> seq<int list>