I have the following recursively defined function:
fun foo(n: int): int =
ifcase
| n = 0 => 0
| n = 1 => 1
| n = 2 => 1
| (* else *) => foo(n-1) + foo(n-3)
// end of [ifcase]
How can I implement foo
based on tail-recursion only.
You can do the followings, where the function
loop
is a tail-recursive function that keeps track of all necessary intermediate states. With tail-call optimization, this one will be optimized into a loop within a single frame, which is much faster thanfoo
.