The canonical function to demonstrate recursion is the factorial() function. I tried a simple implementation of it myself and came up with this:
factorial <- function(x){
if(x==1)
return( 1)
else
return(x*factorial(x-1))
}
From my survey of the topic, there seems to be some debate about whether it's better to use recursion or simple iteration. I wanted to see how R implements it and found a factorial() function in the gregmisc package. I thought I'd find something like my implementation or instead a regular iteration. What I found this:
> factorial
function (x)
gamma(x + 1)
<environment: namespace:base>
So the answer to my question of whether R prefers recursion or iteration is "neither". At least in this implementation. Are recursive functions avoided in R for good reason?
Update:
gregmisc version:
>ptm <- proc.time()
> factorial(144)
[1] 5.550294e+249
> proc.time() - ptm
user system elapsed
0.001 0.000 0.001
my version:
> factorial(144)
[1] 5.550294e+249
> proc.time() - ptm
user system elapsed
0.002 0.001 0.006
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…