stevieb has asked for the wisdom of the Perl Monks concerning the following question:
While I'm at it today, I figure I may as well bow again to our Glorious Monks.
Recursion to some is a simple topic to tackle mathematically, but I have had a very difficult time visually comprehending the timeless fib() example. I don't know why, but I just can't grasp how the end result becomes, because I can't exactly identify how the top-level call enumerates its value.
To the best of my ability, I've tried to print everything out, but I *still* can't grasp what is returned to what, and on what basis a fib(N) call figures out the final figures. I have (semi-broken) code below that I wrote to help me follow codeflow, but I almost need a picture.
I don't mind being the only one who just can't grasp this, or the only one who has spoken up. Any type of figurative help would be immensely appreciated:
#!/usr/bin/perl use warnings; use strict; fib( 5, 0 ); my $count = 0; my $sub_1_count = 0; my $sub_2_count = 0; sub fib { my $num = shift; my $recurse_sub = shift; $count++; print "\nEntering main\n"; print "Iteration: $count\n"; print "Call: sub($recurse_sub)\n"; print "Working num: $num\n"; if ($num <= 2) { print "Returning 1 called by fib($recurse_sub)\n"; return 1; } else { $sub_1_count++; print "Entering fib($recurse_sub), call $sub_1_count\n"; my $x = fib($num-1, -1); $sub_2_count++; print "Entering fib($recurse_sub), call $sub_2_count\n"; my $y = fib($num-2, -2); print "Returning fib(-1) + fib(-2)\n"; print "Result: $x $y\n"; return $x + $y; } }
Anything you can add to spark an *OMFG* realization appreciated
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Visualizing recursion with the fib() example
by BrowserUk (Patriarch) on Mar 18, 2012 at 01:31 UTC | |
Re: Visualizing recursion with the fib() example
by Anonymous Monk on Mar 18, 2012 at 00:51 UTC | |
by Anonymous Monk on Mar 18, 2012 at 01:25 UTC | |
by stevieb (Canon) on Mar 18, 2012 at 00:55 UTC | |
by Anonymous Monk on Mar 18, 2012 at 01:33 UTC | |
Re: Visualizing recursion with the fib() example
by stevieb (Canon) on Mar 18, 2012 at 02:08 UTC |