Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:
I thought that the Fibonacci series would be a good place to start, because unless you know one of the formulas, the previous two results are required for the next number in the sequence. Closures can remember things can't they?
#!/usr/bin/perl -w use strict; sub fibonacci { my ($low, $high) = (1, 0); return sub { ($low, $high) = ($high, $low + $high); return $high; }; } my $iterator = fibonacci(); print $iterator->(), $/ for 1 .. 20;
sub fibonacci { my $fib = shift; return $fib if ! $fib || $fib == 1; my ($low, $high) = (1, 0); my $iterate = sub { ($low, $high) = ($high, $low + $high); return $high; }; $iterate->() for 1 .. $fib; return $high; } print fibonacci(0), $/;
#!/usr/bin/perl -w use strict; sub fibonacci { my $fib = shift; return $fib if ! $fib || $fib == 1; my ($low, $high) = (1, 0); for (1 .. $fib) { ($low, $high) = ($high, $low + $high); } return $high; } print fibonacci(20), $/;
So after my long winded lead in, my question is "What is?". In particular, what are some recursive functions that you have personally made iterative? Did you use closures? Would the use of closures made it easier or just got in the way like it did for me? Can I see the code? Enquiring minds want to know....
Cheers - L~R
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Recursive to Iterative using Closures (Fun with Fibonacci)
by demerphq (Chancellor) on Sep 12, 2003 at 12:56 UTC | |
by Limbic~Region (Chancellor) on Sep 12, 2003 at 13:13 UTC | |
by Abigail-II (Bishop) on Sep 12, 2003 at 14:33 UTC | |
|
Re: Recursive to Iterative using Closures (Fun with Fibonacci) (examples)
by tye (Sage) on Sep 12, 2003 at 15:12 UTC |