fac = function n -> f if n <= 1 f = 1; else f = n * this(n - 1); end endInside 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); ... endHere 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 endNote 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 endwhich can be called as follows
>> fib(10, fib) 89oz 2009-12-22