功能PHP库

v0.2.1 2024-08-27 09:54 UTC

This package is auto-updated.

Last update: 2024-09-27 10:12:18 UTC


README

该库提供了一系列常用的、数据后缀的、函数式编程范式中的柯里化函数。

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

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

API

完整的API文档可以在docs/api.md中找到。

安装

composer require andres-ml/fpl

函数或常量

由于PHP的工作方式,如果我们想将函数作为参数传递,我们需要一个单独的use语句。我们有两种方法来规避这种行为:

  • 使用命名空间
use Aml\Fpl;

$lastWord = Fpl\compose(Fpl\last, Fpl\partial('explode', ' '));
$lastWord('some words in a sentence'); // 'sentence'
  • 利用自动柯里化。这仅适用于具有至少1个固定参数的函数;否则,调用函数将解析它。
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'

如果您愿意,可以使用原始函数定义。注意,这些不是柯里化的,也没有对应的const版本。

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

数组和迭代器

与列表相关的函数在接收数组参数时返回数组,但在接收迭代器时返回迭代器(因此可以表现出惰性)。您可以通过使用toIterator来强制初始数组表现出惰性,或者通过使用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]

代码生成

函数定义在src/api/*.php中。它们分布在不同的文件中,但共享Aml\Fpl\functions命名空间。所有不在以下划线_开头的文件中定义的函数都将被解析并添加到build/api.php中,作为其柯里化版本的调用。

可以通过运行make code来生成代码,它使用src/build.php

文档也可以通过运行make docs自动生成,它使用src/make-docs.php

测试

测试是通过phpunit完成的:使用./vendor/bin/phpunit testsmake test

关于性能的注意

自动柯里化和自动数组/迭代器支持会有性能开销。在时间敏感的循环中使用时要小心;原生array_map始终比其他map的实现更快。