【发布时间】:2011-12-12 13:41:47
【问题描述】:
这个问题和这个previous thread有关。
我按照 Tomas 的建议使用了这段代码,一切正常:
let GetSameColorNeighs (grid:Option<Ball>[,], row, col, color:Color) =
let rec loop (row, col) = seq {
if not (row < 0 || col < 0 || row > MaxLineNumber - 1
|| col > BallsPerLine - 1) then
let ball = grid.[row,col]
match ball with
| Some(ball) ->
if (!ball.visited = false || not <| ball.color.Equals(color)) then
// Not sure what you want here - yield items using 'yield'?
// [row , col]
else
ball.visited := true
yield row, col // Add single item to results
yield! loop(row + 1, col + 1) // Add all generated to results
yield! loop(row - 1, col - 1) // -- || --
| None -> () }
loop(row, col) |> Seq.toList
上面的代码遍历“球”的数组 2d 并返回具有相同颜色的相邻球的索引列表。
现在我必须修改函数,使其还返回一个布尔值,指示列表中的至少一个球是否满足特定条件。我以这种方式更改了代码,但似乎无法在该代码中分配可变值:
let GetSameColorNeighs (grid:Option<Ball>[,], row, col, color:Color) : List<int * int> * bool =
let mutable b : bool = false
let rec loop (row, col) = seq {
if not (row < 0 || col < 0 || row > MaxLineNumber - 1
|| col > BallsPerLine - 1) then
let ball = grid.[row,col]
match ball with
| Some(ball) ->
if (ball.visited = true || not <| ball.color.Equals(color)) then
()
else
//HERE's THE PROBLEM
if (ball_satisfy_a_certain_condition) then
b <- true
ball.visited := true
yield row, col // Add single item to results
yield! loop(row + 1, col + 1) // Add all generated to results
yield! loop(row - 1, col - 1) // -- || --
| None -> () }
loop(row, col) |> Seq.toList, b
好像闭包不能获取可变变量(不知道是什么意思)。
所以我有两个问题:
- 为什么上面对可变变量的赋值是错误的?
- 我应该如何重构我的代码来实现这个目标?
【问题讨论】:
-
更改为“让 b = ref false”
标签: recursion f# closures mutable