I am new to F# and was reading about tail recursive functions and was hoping someone could give me two different implementations of a function foo - one that is tail recursi
An attempt at a shorter explanation than in the other examples:
let rec foo n =
match n with
| 0 -> 0
| _ -> 2 + foo (n-1)
let rec bar acc n =
match n with
| 0 -> acc
| _ -> bar (acc+2) (n-1)
Here, foo
is not tail-recursive, because foo has to call foo
recursively in order to evaluate 2+foo(n-1)
and return it.
However, bar
ís tail-recursive, because bar
doesn't have to use the return value of the recursive call in order to return a value. It can just let the recursively called bar
return its value immediately (without returning all the way up though the calling stack). The compiler sees this and optimized this by rewriting the recursion into a loop.
Changing the last line in bar
into something like | _ -> 2 + (bar (acc+2) (n-1))
would again destroy the function being tail-recursive, since 2 +
leads to an action that needs to be done after the recursive call is finished.