F# recursive function in strange endless loop
f#, f#-interactive
Solution
I suspect you have multiple definitions of `nextEven`. That's the only explanation for your second example compiling. Repro:
module A =
let rec nextEven(x) =
let y = x + 1
if y % 2 = 0 then y
else nextEven y
open A //the function below will not compile without this
let nextEven(x) =
let y = x + 1
if y % 2 = 0 then y
else nextEven y //calling A.nextEven
Try resetting your FSI session.
Problem
I am very green when it comes to F#, and I have run across a small issue dealing with recursive functions that I was hoping could help me understand. I have a function that is supposed to spit out the next even number: ``` let rec nextEven(x) = let y = x + 1 if y % 2 = 0 then y else nextEven y // This never returns.. nextEven 3;; ``` I use the 'rec' keyword so that it will be recursive, although when I use it, it will just run in an endless loop for some reason. If I rewrite the function like this: ``` let nextEven(x) = let y = x + 1 if y % 2 = 0 then y else nextEven y ``` Then everything works fine (no rec keyword). For some reason I though I needed 'rec' since the function is recursive (so why don't I?) and why does the first version of the function run forever ? EDIT Turns out this was a total noob mistake. I had created multiple definitions of the function along the way, as is explained in the comments + answers.