-
Notifications
You must be signed in to change notification settings - Fork 16
nspl\f
Provides functions that act on other functions. Helps to write code in functional programming paradigm.
Identity function. Returns passed value.
assert(1 === id(1));
Applies given function to arguments and returns the result
assert([1, 3, 5, 7, 9] === apply('range', [1, 10, 2]));
Returns new partial function which will behave like $function
with predefined left arguments passed to partial
$sum = function($a, $b) { return $a + $b; };
$inc = partial($sum, 1);
Returns new partial function which will behave like $function
with predefined right arguments passed to rpartial
$cube = rpartial('pow', 3);
Returns new partial function which will behave like $function
with predefined positional arguments passed to ppartial
$oddNumbers = ppartial('range', array(0 => 1, 2 => 2));
Returns function which accepts arguments in the reversed order
Returns new function which applies each given function to the result of another from right to left
compose(f, g, h)
is the same as f(g(h(x)))
use const \nspl\a\flatten;
use const \nspl\a\map;
use function \nspl\f\compose;
use function \nspl\f\partial;
use function \nspl\f\rpartial;
$flatMap = compose(rpartial(flatten, 1), map);
assert(['hello', 'world', 'foo', 'bar'] === $flatMap(partial('explode', ' '), ['hello world', 'foo bar']));
Passes $input
to composition of functions (functions have to be in the reversed order)
use const \nspl\op\sum;
use const \nspl\a\filter;
use const \nspl\a\map;
use const \nspl\a\reduce;
use function \nspl\f\partial;
$isEven = function($x) { return $x % 2 === 0; };
$square = function($x) { return $x * $x; };
// sum of squares of all even numbers less than 20
$sum = pipe(
range(1, 20),
partial(filter, $isEven),
partial(map, $square),
partial(reduce, sum)
);
Alias for the pipe
Returns a curried version of the function. If you are going to curry a function which reads args with func_get_args()
then pass a number of args as the 2nd argument.
If the second argument is true then curry function with optional args otherwise curry it only with required args. Or you can pass the exact number of args you want to curry.
Returns normal (uncurried) version of a curried function
Returns memoized $function
which returns the cached result when the same inputs occur again
$f = function($arg) {
echo sprintf("Performing heavy calculations with '%s'\n", $arg);
return $arg;
};
$memoized = memoized($f);
echo $memoized('Hello world!') . "\n";
echo $memoized('Hello world!') . "\n";
which outputs
Performing heavy calculations with 'Hello world!'
Hello world!
Hello world!
nspl\f
provides all these functions as callbacks in its constants which have the same names as the functions.
use const \nspl\a\map;
use const \nspl\a\filter;
$incListItems = partial(map, function($v) { return $v + 1; });
$filterNumbers = partial(filter, 'is_numeric');
Check more \nspl\f
examples here.