functional-php / pattern-matching
PHP 的自动解构模式匹配。
1.0.0
2021-07-11 07:23 UTC
Requires
- php: >=5.6.0
Requires (Dev)
- atoum/atoum: ^3 || ^4
- atoum/reports-extension: ^3 || ^4
- friendsofphp/php-cs-fixer: ~2 || ~3
README
模式匹配是检查一系列标记与模式的过程。它不同于模式识别,因为匹配需要是精确的。这个过程不仅像 switch 语句一样匹配,还像 PHP 中的 list
构造一样分配值,这个过程称为 解构。
大多数函数式语言都将它实现为核心特性。以下是一些 Haskell 中的小例子
fact :: (Integral a) => a -> a fact 0 = 1 fact n = n * fact (n-1) head :: [a] -> a head xs = case xs of [] -> error "empty list" (x:_) -> x firstThree :: [a] -> (a, a, a) firstThree (x:y:z:_) = (x, y, z) firstThree _ = error "need at least 3 elements"
如果您想了解更多关于这个主题的信息,可以访问维基百科: 模式匹配
安装
composer require functional-php/pattern-matching
基本用法
由于我们无法扩展 PHP 的语法,因此选择了基于数组的语法。键代表模式,值是要调用的函数或如果您想对此值不采取任何行动的常量。
让我们看看我们如何实现 3 个 Haskell 示例
use FunctionalPHP\PatternMatching as m; $fact = m\func([ '0' => 1, 'n' => function($n) use(&$fact) { return $n * $fact($n - 1); } ]); $head = m\func([ '(x:_)' => function($x) { return $x; }, '_' => function() { throw new RuntimeException('empty list'); } ]); $firstThree= m\func([ '(x:y:z:_)' => function($x, $y, $z) { return [$x, $y, $z]; }, '_' => function() { throw new RuntimeException('need at least 3 elements'); } ]);
如果您想有一个增强版的 switch
语句或不喜欢匿名函数,也可以使用 match
函数
use FunctionalPHP\PatternMatching as m; function factorial($n) { return m\pmatch([ '0' => 1, 'n' => function($n) use(&$fact) { return $n * factorial($n - 1); } ], $n); } echo m\pmatch([ '"toto"' => 'first', '[a, [b, c], d]' => 'second', '[a, _, (x:xs), c]' => 'third', '_' => 'default', ], [1, 2, ['a', 'b'], true]); // third
如果您只想解构值,也有相应的辅助函数
use FunctionalPHP\PatternMatching as m; print_r(m\extract([1, 2, ['a', 'b'], true], '[a, _, (x:xs), c]')); // Array ( // [a] => 1 // [x] => a // [xs] => Array ( [0] => b ) // [c] => 1 // )
模式
以下是可用的模式的快速回顾
测试
您可以使用以下方式运行库的测试套件
composer test
测试报告将在 reports
目录中可用。
贡献
欢迎任何贡献
- 想法
- 拉取请求
- 问题