Functional PHP library

v0.2.0 2020-03-30 16:42 UTC

This package is auto-updated.

Last update: 2024-04-13 11:02:28 UTC


README

This library provides a series of curried, data-last functions commonly used within the functional programming paradigm.

use function Aml\Fpl\{compose, partial};
use const Aml\Fpl\{last};

$lastWord = compose(last, partial('explode', ' '));
$lastWord('some words in a sentence'); // 'sentence'

API

Full api documentation can be found in docs/api.md

Installation

composer require andres-ml/fpl

Function or const

As we can see above, due to how PHP works, we need a separate use statement if we want to pass a function as a parameter. We have two ways to circumvent that behavior:

  • Use the namespace
use Aml\Fpl;

$lastWord = Fpl\compose(Fpl\last, Fpl\partial('explode', ' '));
$lastWord('some words in a sentence'); // 'sentence'
  • Make use of automatic currying. This is valid only for functions that have at least 1 fixed argument; otherwise calling the function would resolve it.
use function Aml\Fpl\{compose, partial, last};

// note that we use 'last()' instead of just 'last'
$lastWord = compose(last(), partial('explode', ' '));
$lastWord('some words in a sentence'); // 'sentence'

If you want, you can use the original function definitions instead. Note that these are not curried and don't have their corresponding const versions.

use function Aml\Fpl\functions\{map};

Arrays and iterators

List-related functions return an array when they receive an array parameter, but they return iterators when receiving iterators (and can thus behave lazily). You can force laziness over an initial array by previously using toIterator or finish off with an array by ending with toArray:

use Aml\Fpl;

$lowerThan4 = function($x) { return $x < 4; };

Fpl\takeWhile($lowerThan4, [0, 1, 2, 3, 4, 5]); // [0, 1, 2, 3]

$pickLowerThan4 = Fpl\compose(
    Fpl\toArray
    Fpl\takeWhile($lowerThan4),
    Fpl\counter
);

$pickLowerThan4(); // [0, 1, 2, 3]

Code generation

Functions are defined on src/api/*.php. They are split among different files but share the Aml\Fpl\functions namespace. All functions defined on those files not beginning with an underscore _ will be parsed and added to build/api.php as calls to their curried versions.

Code can be generated by running make code, which uses src/build.php.

Documentation is also automatically generated through make docs, which uses src/make-docs.php.

Testing

Testing is done through phpunit: ./vendor/bin/phpunit tests or make test

Note on performance

Automatic currying and automatic array/iter support have a performance overhead. Be wary of using them in a time-critical loop; a native array_map will always be faster than other implementations of map.