MATLAB Language Useful tricks Functional Programming using Anonymous Functions


Example

Anonymous functions can be used for functional programming. The main problem to solve is that there is no native way for anchoring a recursion, but this can still be implemented in a single line:

if_ = @(bool, tf) tf{2-bool}();

This function accepts a boolean value and a cell array of two functions. The first of those functions is evaluated if the boolean value evaluates as true, and the second one if the boolean value evaluates as false. We can easily write the factorial function now:

fac = @(n,f) if_(n>1, {@()n*f(n-1,f), @()1});

The problem here is that we cannot directly invoke a recursive call, as the function is not yet assigned to a variable when the right hand side is evaluated. We can however complete this step by writing

factorial_ = @(n)fac(n,fac);

Now @(n)fac(n,fac) evaulates the factorial function recursively. Another way to do this in functional programming using a y-combinator, which also can easily be implemented:

y_ = @(f)@(n)f(n,f);

With this tool, the factorial function is even shorter:

factorial_ = y_(fac);

Or directly:

factorial_ = y_(@(n,f) if_(n>1, {@()n*f(n-1,f), @()1}));