September 17, 2012

# Functional Programming in MATLAB (Yes, that MATLAB)

I spent a little bit of time implementing some functional programming tools in MATLAB. I called the package "functools", and you can get it from Github.

So far, I've implemented the following:

• compose
• apply
• partial
• if (functional conditional branching)
• reduce
• map
• Y combinator

Why would you want to do it? Same reason you're using MATLAB instead of C. Performance may be worse, but you, the programmer, can do more faster. Look how easy it is to whip up a "join" function:

 1 2 3 4 `join = @(sep, lst) ...` ` functools.if(~ischar(sep), @()[], @() ...` ` functools.reduce(@(x, y) [x sep y], ...` ` functools.map(@num2str, lst)));`

## Surprisingly Versatile Anonymous Functions

MATLAB's first-class function capabilities are surprisingly advanced.

## Function composition

Compose, apply and partial simplify many aspects of working with MATLAB, a language with an extensive toolset of complex functions that often take many inputs. Here's my favorite example:

```>> a = 1;
>> b = ones(2, 1) / 2;
>> movingavg2 = functools.partial(@filter, b, a);
>> movingavg2(1:4)

ans =

0.5000    1.5000    2.5000    3.5000```

## Collection operations

Matlab's loop syntax is just ok, but man, do I ever miss map sometimes.

## Y combinator

You might be thinking, "but I thought the Y combinator was only useful for languages that include first-class functions but not recursion." Well, for the meta-language created by this package, this is exactly the case, which is why it includes a Y combinator function built in. Here's the canonical factorial example:

 1 2 3 4 `fact = functools.Y(@(self) @(n) ...` ` functools.if(n < 2,...` ` @() 1,` ` @() n * self(n - 1));`

If you've read this far, you should really try it out. I've found MATLAB just a bit more enjoyable since I started to use these tools.