【发布时间】:2012-01-15 10:50:20
【问题描述】:
我正在尝试编写一个返回 List 的递归函数,但我在语法上遇到了一些问题。
当递归结束时,函数应该返回一个空列表,否则一个元组 (int * int) 与递归调用自身返回的 List 合并:
let rec foobar () : List<int * int> =
if (recursionIsEnded) then
[]
else
foobar () :: (10, 10) // this is wrong
// (10,10) works, but I need to concatenate it with the elements returned by foobar recursive call
有人可以向我解释我做错了什么吗?
编辑:
我会尽量提供更多细节。 其实我的功能有点复杂。我正在遍历一个二维数组并构建一个包含满足特定条件的数组索引元素的元组列表。其实这是我的代码:
let rec GetSameColorNeighs(grid : Option<Ball> [,], row : int , col : int, color : Microsoft.Xna.Framework.Color) : List<int * int> =
if (row < 0 || col < 0 || row > MaxLineNumber - 1 || col > BallsPerLine - 1) then
[]
else
let ball = grid.[row,col]
match ball with
|Some(ball) ->
if (!ball.visited = false || not <| ball.color.Equals(color)) then
[row , col]
else
ball.visited := true
(row,col) ::GetSameColorNeighs(grid, row + 1, col + 1, color) :: GetSameColorNeighs(grid, row - 1, col - 1, color)
|None -> []
所以这里还有 2 个问题:):
-
如何修改下面一行才能编译?
(row,col) ::GetSameColorNeighs(grid, row + 1, col + 1, color) :: GetSameColorNeighs(grid, row - 1, col - 1, color) 有没有更好的方法来做到这一点?
我不关心列表的元素顺序。
【问题讨论】:
标签: list syntax recursion f# tuples