I’m trying to write a recursive function that return a List < int * int>, but I’m having some trouble with the syntax.
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?
EDIT:
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 -> []
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).
Based on your update, I’d prefer a mutable solution. Something like