vector/core

PHP的函数式编程库

v7.0.1 2020-03-10 01:24 UTC

README

Vector Core Badge Status

简介

Vector赋予你PHP的函数式超级能力。

  • 演变

    • 原生PHP
        array_sum(
            array_map(
                fn($a) => $a + 1,
                [1, 2, 3]
            )
        );
        // 9
      • 👎 1或2个以上的函数链难以维护
    • Laravel 集合
        collect([1, 2, 3])
            ->map(fn($a) => $a + 1)
            ->sum();
            // 9
      • 👍 1或2个以上的函数链难以维护
      • 👎 很遗憾,你无法以同样的优雅方式对每种类型都这样做(仅适用于集合)
    • Vector
         vector([1, 2, 3])
             ->pipe(Arrays::map(Math::add(1))) // or `fn($a) => $a + 1)` 
             ->pipe(Math::sum())();
             // [2, 3, 4]
      • 👍 与集合的工作方式非常相似,但仅接受并返回正常数组(无需-toArray())
      • 👍 在其他所有方面也几乎与集合一样工作!
      • 👎 很遗憾,它是一个额外的依赖(我们还没有本地的管道操作符https://wiki.php.net/rfc/pipe-operator-v2
  • 您可以将柯里化添加到任何函数中,而不仅限于Vector内置函数。

    • Module::curry('explode')(',')('a,b,c')(PHP_INT_MAX) // ['a', 'b', 'c']

PHP版本支持

  • 8.0+

安装

composer require vector/core

看看更多代码

更多自动柯里化。

$addOne = Arrays::map(Math::add(1));
$addOne([1, 2, 3]); // [2, 3, 4]

一等组合(函数式管道)。

$addSix = Lambda::compose(Math::add(4), Math::add(2)); // (Or ::pipe for the opposite flow direction)
$addSix(4); // 10;

模式匹配(包括Maybe & Result monads)。

Pattern::match([
    fn(Just $value) => fn ($unwrapped) => $unwrapped,
    fn(Nothing $value) => 'nothing',
])(Maybe::just('just')); // 'just'

细粒度控制流(无需try/catch)。

$errorHandler = function (Err $err) {
    return Pattern::match([
        function (QueryException $exception) {
            Log::info($exception);
            return response(404);
        },
        function (DBException $exception) {
            Log::error($exception);
            return response(500);
        },
    ]);
};

return Pattern::match([
    fn(Ok $value) => fn (User $user) => $user,
    $errorHandler
])(Result::from(fn() => User::findOrFail(1)));

使用自动柯里化方法创建自己的模块

use Vector\Core\Curry;
use Vector\Core\Module;

class MyModule
{
    use Module;
    
    #[Curry]
    protected static function myCurriedFunction($a, $b)
    {
        return $a + $b;
    }
}