Console.WriteLine above increment, count from 0 to 9
I don't understand whats going on. I expected the results to be:
Console.WriteLine above increment, count from 0 to 9.
Console.WriteLine below increment, count from 1 to 9.
Can someone please explain whats going on here?
Edit: Apparently I cannot add a picture\link
Code is:
let rec test x =
if x < 10 then
Console.WriteLine(x)
test (x+1)
test 0
and
let rec test x =
if x < 10 then
test (x+1)
Console.WriteLine(x)
test 0
In the second case where you get a count-down from 9 to 0, what's happening is the recursion bottoms out first, then you print as it unwinds. Inlining the code to unroll the recursion, what you are executing looks like
let test x =
if x < 10 then
let x1 = x + 1
if x1 < 10 then
let x2 = x1 + 1
if x2 lt 10 then
let x3 = x2 + 1
...
Console.WriteLine(x3)
Console.WriteLine(x2)
Console.WriteLine(x1)
Console.WriteLine(x)which makes it obvious that the first line written is from the deepest call.