Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tail recursion on R Statistical Environment

Does R support proper tail recursion and where can I find documentation about this?

like image 983
Paulo Silva Filho Avatar asked Nov 03 '12 12:11

Paulo Silva Filho


People also ask

Should I always use tail recursion?

Tail-recursive functions are considered better than non-tail-recursive functions — the compiler can easily optimize the tail-recursive function as there is nothing left to do in the current function after the recursive call. Hence, the function's stack frame need not be saved.

Is tail recursion good for programming?

The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed.

What is tail recursion give example?

Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive.

Does tail recursion use a lot of memory?

smp of tail-recursive version will use 2.5G ~ 3G memory while the body-recursive only use around 1G.


1 Answers

It's quite easy to find out that R does not support tail recursion optimization:

f <- function(n) {
if (n != 0) f(n-1)
}
f(100000)
# Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

Had tail calls been optimized to jumps, then this function would have terminated without problems.

like image 95
Fred Foo Avatar answered Sep 25 '22 20:09

Fred Foo