Siler
Search…
λ Functional
Functional programming treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is declarative, which means expressions instead of statements.
Siler is bundled with the Siler\Functional namespace. It brings some function declarations that aids the work with another first-class and high-order PHP functions!

identity()

Returns a Closure that returns its given arguments.
1
use Siler\Functional as λ;
2
3
array_map(λ\identity(), [1, 2, 3]);
4
// [1, 2, 3]
Copied!
Doesn't seem useful at first, but working with the functional paradigm, you'll find the reason shortly.

always($value)

Almost like identity(), but it always returns the given value.
1
use Siler\Functional as λ;
2
3
array_map(λ\always('foo'), range(1, 3));
4
// [foo, foo, foo]
Copied!

if_else(callable $cond) -> $then -> $else

A functional if/then/else.
1
use Siler\Functional as λ;
2
3
$pred = λ\if_else(λ\equal('foo'))(λ\always('is foo'))(λ\always('isnt foo'));
4
5
echo $pred('foo'); // is foo
6
echo $pred('bar'); // isnt foo
Copied!

partial(callable $callable, ...$partial)

Partial application refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function
, we might fix (or 'bind') the first argument, producing a function of type
. https://en.wikipedia.org/wiki/Partial_application
Nothing like a good example:
1
use Siler\Functional as λ;
2
3
$add = function ($a, $b) {
4
return $a + $b;
5
};
6
7
$add2 = λ\partial($add, 2);
8
9
echo $add2(3); // 5
Copied!
Works with any callable:
1
use Siler\Functional as λ;
2
3
$explodeCommas = λ\partial('explode', ',');
4
print_r($explodeCommas('foo,bar,baz'));
5
6
/**
7
* Array
8
* (
9
* [0] => foo
10
* [1] => bar
11
* [2] => baz
12
* )
13
*/
Copied!

match(array $matches)

A pattern-match attempt. Truthy Closure evaluations on the left calls and short-circuits evaluations on the right.
1
use Siler\Functional as λ;
2
3
$nameOf = λ\match([
4
[λ\equal(1), λ\always('one')],
5
[λ\equal(2), λ\always('two')],
6
[λ\equal(3), λ\always('three')],
7
]);
8
9
echo $nameOf(1); // one
10
echo $nameOf(2); // two
11
echo $nameOf(3); // three
Copied!
There are a lot more of them. A good place it check it out are the tests.
Last modified 2yr ago