The function could be more simply (and correctly, since the function specified didn't give the right values) written as:
Or even:sub fibonacci { return 1 if $_[0] < 3; fibonacci($_[0]-1) + fibonacci($_[0]-2); }
Where the number returned is the nth number in the fibonacci sequence, n being the number passed to the function:sub fibonacci { $_[0] < 3 ? 1 : fibonacci($_[0]-1) + fibonacci($_[0]-2); }
1 1 2 3 5 8 13 etc.
Let's say you call the function with 4:
(4) Is 4 < 3? No. Return (4-1) + (4-2).
(4-1) Is 3 < 3? No. Return (3-1) + (3-2).
(3-1) Is 2 < 3? Yes. Returning 1.
(3-2) is 1 < 3? Yes. Returning 1.
(4-1) Returning 1 + 1.
(4-2) Is 2 < 3? Yes. Returning 1.
(4) Returning 2 + 1.
Answer returned is 3, which is the 4th number in the sequence.
See, every number in the sequence is built off the previous two values, each of which is built off the two values previous to it, and so on - all the way back to the first and second values (1 and 2 are < 3), which are 1. If the value passed to the function is 1 or 2, it knows to return 1; otherwise it calls itself twice to determine the previous two numbers in the sequence.
In reply to Re: Puzzled by Recursion.
by TedPride
in thread Puzzled by Recursion.
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |