Recursion in ActionScript

Our example demonstrates recursive functions in ActionScript. Here’s a classic example of calculating factorials recursively.

package {
    import flash.display.Sprite;
    import flash.text.TextField;

    public class Recursion extends Sprite {
        public function Recursion() {
            var output:TextField = new TextField();
            output.width = 400;
            output.height = 300;
            addChild(output);

            // This fact function calls itself until it reaches the
            // base case of fact(0).
            function fact(n:int):int {
                if (n == 0) {
                    return 1;
                }
                return n * fact(n-1);
            }

            output.text += "Factorial of 7: " + fact(7) + "\n";

            // Closures can also be recursive in ActionScript
            var fib:Function = function(n:int):int {
                if (n < 2) {
                    return n;
                }
                // Since fib was previously declared, ActionScript
                // knows which function to call with fib here.
                return fib(n-1) + fib(n-2);
            };

            output.text += "Fibonacci of 7: " + fib(7);
        }
    }
}

This ActionScript code defines a class Recursion that extends Sprite. In the constructor, we create a TextField to display our output.

We define a recursive fact function to calculate factorials. This function calls itself until it reaches the base case of fact(0).

We then demonstrate the use of a recursive closure with the Fibonacci sequence. In ActionScript, closures can be recursive without any special declaration.

To run this code, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would be:

Factorial of 7: 5040
Fibonacci of 7: 13

This example showcases how ActionScript supports recursive functions and closures, providing a powerful tool for solving problems that have a naturally recursive structure.