t3x.org / t3x / t3x-manual / 281.html
 
T3X - A Minimum Procedural Language
Version 8.1.5, Online Edition
Copyright(C) 1996-2004
Nils M Holm
 
Previous:
2.8 Procedures
TOC | Index | Back Next:
2.8.2 Mutually Recursive Procedures

2.8.1 Recursive Procedures

It is perfectly safe for a procedure to call itself. Since the declaration of a procedure takes place while parsing its head (consisting of its name and its argument list), the declaration is already in effect when the compiler processes the body. Therefore, a procedure may recurse into itself:

fac(n) RETURN n=1-> 1: fac(n-1)*n;

This small example computes n! (the factorial of n), which is defined as

1 * ... * n-1 * n

For the trivial case n=1, it simply returns 1. To compute n! where n>1, it first computes (n-1)! and then multiplies the result with n. To compute the factorial of n-1, it calls itself. Since the value of the argument of the recursive call is decremented by one at each level of recursion, it will finally reach 1 and the procedure will start returning.

Recursion is safe in T3X, because local variables (which include formal arguments) are created freshly each time a declaration is passed. Therefore, the symbol n in the above example denotes different variables at each level of recursion. To see how recursion works, the following program including a modified example of the factorial function is recommended:

MODULE visual_fac(t3x, string);

OBJECT  t[t3x], str[string];

fac(n) DO VAR b::30;
        ie (n=1) do
                t.write(T3X.SYSOUT, " 1", 3);
                return 1;
        end
        else do
                t.write(T3X.SYSOUT, str.format(b, " %D *", [(n)]),
                        str.length(b));
                return n*fac(n-1);
        end
END

DO var b::80;
        t.write(T3X.SYSOUT, "fac(7) =", 8);
        t.write(T3X.SYSOUT, 
                str.format(b, " = %D\n", [(fac(7))]),
                str.length(b));
END

Of course, the usual restrictions concerning the use of global memory and other shared resources in recursive procedures apply also in T3X.

Previous:
2.8 Procedures
TOC | Index | Back Next:
2.8.2 Mutually Recursive Procedures