in reply to Re: Recursive to Iterative using Closures (Fun with Fibonacci)
in thread Recursive to Iterative using Closures (Fun with Fibonacci)

demerphq,
Ok - here is what I "thought" knew and what I was thinking.

Typical recursion case: When a function requires all elements prior to it to be evaluated before it can be evaluated.

If I work forwards instead of backwards, I can remember what I need to as I go. In the case of the Fibonacci series, I only need the last 2. I was thinking that closures would be an ideal way to "remember" and just move forward from the beginning to the desired element.

This indeed worked, but turned out not requiring the closure at all. So I was left wondering.

Cheers - L~R

  • Comment on Re: Re: Recursive to Iterative using Closures (Fun with Fibonacci)

Replies are listed 'Best First'.
Re: Recursive to Iterative using Closures (Fun with Fibonacci)
by Abigail-II (Bishop) on Sep 12, 2003 at 14:33 UTC
    Recursion is suitable for problems where you can divide the problem into one or more independent subsets; you can solve the problem for the subsets and use the results to efficient calculate the result for the entire set; and each of the subsets should be significantly smaller than the original set.

    A recursive solution for Fibonacci fails the first requirement, the "sets" are not independent (it also fails the third requirement). Calculating the factorial is also a common example for recursion, but that fails the the third requirement, making that the overhead of calling subs is significant, and it's not compensated by simpler code. Recursion can't really beat:

    my $p = 1; $p *= $_ for 2 .. $n;

    Abigail