Reputation: 179
I have a recursive function in my code that looks like this:
let rec func (a,b)
match (a,b) with
| condition 1 -> func a+1 b
| condition 2 -> print "%s" done
| _ then func a b+1 //<-- It enters here after going into the else ()!!
if a = b then func 0 0
else ()
The problem is that when the match section ends, it goes to the if statement and doesn't match it, which is good. So it goes to "else ()" and should quit the recursion but instead it goes back to the |_ -> print func a b+1
. Why can this happen?
Upvotes: 0
Views: 128
Reputation: 5464
You effectively have two sections of code
a match statement
match (a,b) with
| condition 1 -> func a+1 b
| condition 2 -> print "%s" done
| _ then func a b+1 //<-- It enters here after going into the else ()!!
and then an if/else
if a = b then func 0 0
else ()
Unless "condition 2" is matched, this function will always recurse during the match section and it does not matter that the if/else block does not recurse. I am not sure what you are attempting to achieve, but maybe you want a match/when
match (a,b) with
| condition 1 -> func a+1 b
| condition 2 -> print "%s" done
| _,_ when a = b -> func 0 0
| _ -> func a b+1 //<-- It enters here after going into the else ()!!
Now "condition 2" is your stop case. Is "condition 2" an active pattern?
Upvotes: 1
Reputation: 179
I got where my problem was. The recursion was called N times, so when the recursion ended within the match statement, it had to go N times into the if statement. I don't know why while debugging it would show the |_ -> else()
highlighted, but I already understood the problem and solved it. Thank you guys!
Upvotes: 0
Reputation: 5688
Presumably, after reaching
| condition 2 -> print "%s" done
then if a=b
your program continues by doing
if a = b then func 0 0
(Or maybe it returns, then do the same call higher up the call chain.) Likely that recursive call then takes you to
| _ then func a b+1
Because of lightweight syntax, the if
after the match
is always executed.
Upvotes: 0