[R] Problem with recursion

R. Michael Weylandt michael.weylandt at gmail.com
Sat Nov 10 09:28:07 CET 2012


On Sat, Nov 10, 2012 at 7:41 AM, Haszun <crazystef13 at tlen.pl> wrote:
> I know that maybe it will be stupid question.
>
> What iswrong  with it (i think that i have to do the "stop moment", but i
> dont know how)
>
> fibbonacci=function(x) {
> while(x>0) {
> if (x==1 || x==2) {
> return(1)
> } else fibbonacci(x-1)+fibbonacci(x-2)
> }
> }

Just a hint: do you need a while condition? If so, might a return()
help you out? If not, what's the cleanest way to eliminate it? Note
that R has the convention that the final value in the function is the
one returned, but that constructs like this can trip you up:

x <- 5
while(x > 0) x <- x - 1
print(.Last.value)

Cheers,
Michael




More information about the R-help mailing list