gpt4 book ai didi

f# - F# 闭包中的可变变量

转载 作者:行者123 更新时间:2023-12-04 22:34:24 24 4
gpt4 key购买 nike

我正在尝试移植一些代码形式 java do 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: The mutable variable 'lastIndex' is used in an invalid way. Mutable variables cannot be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!'.



我该如何解决这个错误?我怎样才能让它更实用?

示例:对于中点 [|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|]}

另请注意,这将执行多次,因此性能至关重要。

最佳答案

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
}

?
ref 非常适合此类用途,并且不被视为可变变量(因为它们不是)。

关于f# - F# 闭包中的可变变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10947309/

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