Recursion

A function may call itself directly or indirectly. This is referred to as recursive function call, and is very common feature of most programming languages. In Shang there are three ways that recursion can be done. First, the keyword this can be used inside the function to call the function object itself. For example
   fac = function n -> f
               if n <= 1
                    f = 1;
               else
                    f = n * this(n - 1);
               end
         end
Inside the function body, this refers the function fac, therefore this(n - 1) is a call to the function itself. The result of calling fac(n) will be the factorial of n, i.e., the product of 1, 2, ..., up to n. This appears to be a neat solution for doing recursion, but when calling a function itself indirectly is needed, it can't help. In this case the best strategy is to define the functions as global variables. The following is an example of indirect recursion.
   global.f = function x -> y
                 ...
                 global.g(3);
                 ...
              end

   global.g = function x -> y
                 ...
                 global.f(3);
                 ...
              end
Here the two functions f and g call each other. We call this indirect recursive function call. Note that direct recursion can be done like this as well.
   global.fac = function n -> f
               if n <= 1
                    f = 1;
               else
                    f = n * fac(n - 1);
               end
         end
Note that the statement f = n * fac(n - 1) can be written as f = n * global.fac(n - 1) as well.

Finally, it's also possible to implement recursion by passing the function to itself as an input argument value (or set it to one of its parameter values). For example:

>> fib = function (n, f) -> s
                if n <= 1
                     s = 1;
                else
                     s = f(n - 1, f) + f(n - 2, f);
                end
   end
which can be called as follows
>> fib(10, fib)
   89

.

oz 2009-12-22