fp4php/fp4php

PHP functional programming library

v0.1.0 2023-09-04 08:52 UTC

This package is auto-updated.

Last update: 2024-04-13 15:28:46 UTC


README

Functional programming utilities for PHP.

psalm level psalm type coverage phpunit coverage

This library extensively uses curried functions and the pipe combinator.

If you don't like the following code:

self::someMethod(
    array_filter(
        array_map(
            fn ($i) => $i + 1,
            [1, 2, 3],
        ),
        fn ($i) => $i % 2 === 0,
    );
);

Or:

self::someMethod(
    ArrayList::fromIterable([/*...*/]),
        ->map(fn ($i) => $i + 1),
        ->filter(fn ($i) => $i % 2 === 0),
);

Then this library might interest you:

<?php

declare(strict_types=1);

use Fp4\PHP\ArrayList as l;

use function Fp4\PHP\Combinator\pipe;

final class App
{
    /**
     * @param list<int> $list
     * @return list<string>
     */
    public function run(array $list): array
    {
        return pipe(
            $list,
            l\map(fn($i) => $i + 1),
            l\filter(fn($i) => 0 === $i % 2),
            self::toString(...),
        );
    }

    /**
     * @param list<int> $list
     * @return list<string>
     */
    public static function toString(array $list): array
    {
        return pipe(
            $list,
            l\map(fn($i) => (string)$i),
        );
    }
}

To learn more about this library, read the following: