I usually see the Fibonaccis start with 0 (i.e. 0, 1, 1, 2, 3, etc), but that's not crucial. As for the function: if you pass it 15, then since 15 isn't < 1, the else is executed and the result is fib(14)+fib(13). But then this produces fib(13)+fib(12)+fib(12)+fib(11), etc. It's easier to follow a simpler case: give the function 3; then you get fib(2)+fib(1) and then fib(1)+fib(0)+fib(0)+fib(-1). Since fib(1) results in fib(0)+fib(-1), the final result is 5. Your function give for 0,1,2,3,4,... the values 1,2,3,5,8,...
chas
(I shortened fibonacci to fib to save space. It does seem rather clever that the parser is able to handle functions that call themselves. I think compilers often implement the recursion in terms of loops; I don't know what Perl does.)

In reply to Re: Puzzled by Recursion. by chas
in thread Puzzled by Recursion. by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.