Did you know that MATLAB has built-in support for closures? Develop for MATLAB in a functional style with functools.
HUGE DISCLAIMER
MATLAB is incredibly slow at applying anonymous functions. Don't use this library for performance,
use it for convenience. I tend to use it for string manipulations mostly.
Tools Included
Specifically, the following tools are implemented:
Basic functional programming operations:
compose - Compose a function out of two or more other functions
apply - Apply a function to a cell array of arguments, as if the elements of the array were individual args
partial - Partially apply a function
rpartial - Right-handed partial
Collection operations
map - Apply a function to each member of a vector/cell array and return a modified collection of the same type
reduce - Reduce (fold) a cell array or vector of values into a single one using repeated function application
Utilities
if_ - Functional branching, wrapping branches in functions to defer execution
nth - Return the nth output argument from calling a function.
Y - The Y combinator. Yes!
All the following examples assume you've done
import functools.*
Examples
Most of these examples are taken from the tests. Sorry if they're a bit contrived.
Rpartial is notable for having a particularly useful function in MATLAB: pre-applying those key/value parameters that almost every
base matlab function has:
% Unfortunately, function application in MATLAB is even slower than its slow for loops.% So, you probably shouldn't use this for math, although you can.map(@(x) x*2, {1, 2, 3}) % => {2, 4, 6}
% Better to use this as a utility functionpwd% => /some/directory
filepaths =map(partial(@fullfile, pwd), {'1.txt', '2.txt', '3.txt', '4.txt'});
filepaths{2} % => '/some/directory/2.txt'
% Wrap functions that refuse to return a value with partial(nth, 0)apply(@disp, {'Disp will choke on this'}) % => ERRORapply(partial(@nth, 0, @disp), {'Disp will actually display this'}) % => [] (But the text is displayed)
% 2nd output of sort is the former indices of the newly-sorted elementsnth(1, @sort, [100, 400, 200, 300]) % => [100 200 300 400]nth(2, @sort, [100, 400, 200, 300]) % => [1 3 4 2]
Y
The Y combinator is a way of making recursive functions in languages which lack
recursion but which have first-class functions, which is true of almost no
language in use today.
But, the meta-language of anonymous functional MATLAB fits this bill perfectly!
Y takes a function that takes one argument, self, which returns an inner function.
In that inner function, you can use self as an application of that inner function!
This is all better explained by example:
fact =Y( ...
@(self) ... % Accepts a function...
@(n) ... % that returns a function ...if_(n<=1, ...
@() 1, ...
@() n*self(n-1))); % ... that uses self recursively.fact(4) % => 24fact(6) % => 720
请发表评论