F#:编写函数以递归方式建立元组列表,语法错误 [英] F# : Writing a function that builds a list of tuples recursively, a syntax error
问题描述
我正在尝试编写一个返回List<的递归函数. int * int>,但是我在语法上遇到了麻烦.
I'm trying to write a recursive function that return a List < int * int>, but I'm having some trouble with the syntax.
该函数应在递归结束时返回一个空列表,否则元组(int * int)与递归调用返回的List合并:
The function should return an empty list when the recursione ends, otherwise a tuple (int * int) merged with a List returned by a recursive call to itself:
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
有人可以向我解释我在做什么错吗?
Could someone explain to me what I'm doing wrong?
我将尝试提供更多细节. 其实我的功能有点复杂.我正在遍历2d数组,并使用满足一定条件的数组索引元素构建元组列表.其实那是我的代码:
I'll try to give more details . Actually my function is a bit more complicated. I'm iterating through a 2d array and build a list of tuples with the array index elements that satisfy a certain condition. Actually that's my code:
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个问题:):
So here's 2 more question :):
-
如何修改下一行以使其编译?
How modify the following row in order to make it compile?
(row,col) ::GetSameColorNeighs(grid, row + 1, col + 1, color) :: GetSameColorNeighs(grid, row - 1, col - 1, color)
还有更好的方法吗?
Is there any better way to do that?
我不在乎列表的元素顺序.
I don't care about the list's elements order.
推荐答案
将内部函数与累加器一起使用可能是最简单的方法(此外,它具有尾部递归功能).
Using an inner function with an accumulator is probably the easiest way to do it (as a bonus it's tail recursive).
let foobar() =
let rec foobar acc =
if (recursionIsEnded) then
List.rev acc
else
foobar ((10, 10)::acc)
foobar []
根据您的更新,我希望使用一种可变的解决方案.像
Based on your update, I'd prefer a mutable solution. Something like
let GetSameColorNeighs(grid : Option<Ball> [,], row : int , col : int, color : Microsoft.Xna.Framework.Color) : List<int * int> =
let results = ResizeArray()
let rec loop (row, col) =
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] //doesn't compile, not sure what to do here
else
ball.visited := true
results.Add(row, col)
loop(row + 1, col + 1)
loop(row - 1, col - 1)
|None -> ()
loop(row, col)
results |> Seq.toList
这篇关于F#:编写函数以递归方式建立元组列表,语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!