in reply to Re: Visualizing recursion with the fib() example
in thread Visualizing recursion with the fib() example

I understand the mathematical equations entirely... what I can't grasp is how Perl is handling the recursion.

Perhaps it is as simple as the math, but it just ain't 'clicking', hence my question.

  • Comment on Re^2: Visualizing recursion with the fib() example

Replies are listed 'Best First'.
Re^3: Visualizing recursion with the fib() example
by Anonymous Monk on Mar 18, 2012 at 01:33 UTC

    I understand the mathematical equations entirely... what I can't grasp is how Perl is handling the recursion.

    Perhaps it is as simple as the math, but it just ain't 'clicking', hence my question.

    Um, yes, its exactly like the math. It didn't click for me either until I wrote it out by hand with a pencil.

    #!/usr/bin/perl -- use strict; use warnings; print fib(5); sub fib { my( $n, $depth ) = @_; $depth ||= 0; print "(d $depth)", " " x $depth, " (n $n)\n"; if ($n < 2) { return $n } fib($n-2, $depth + 1 ) + fib($n-1 , $depth + 1 ); } __END__ (d 0) (n 5) (d 1) (n 3) (d 2) (n 1) (d 2) (n 2) (d 3) (n 0) (d 3) (n 1) (d 1) (n 4) (d 2) (n 2) (d 3) (n 0) (d 3) (n 1) (d 2) (n 3) (d 3) (n 1) (d 3) (n 2) (d 4) (n 0) (d 4) (n 1) 5