yshnb / php-monadic
PHP中的单调型编程
dev-master
2015-06-22 15:34 UTC
Requires (Dev)
- phpunit/phpunit: ~4.7
This package is not auto-updated.
Last update: 2024-09-28 17:28:10 UTC
README
PHP中单调模式库。
类型
此库实现了以下类型(类)
- Identity
- Maybe
- Either
- ListLike(List)
使用方法
安装
您可以从 packagist.org 安装。
composer require yshnb/php-monadic:dev-master
示例
Identity
Identity是一种单调类型,它简单地包装任何值。
<?php
use Monadic\Type\Identity;
$foo = 1;
$identity = Identity::unit($foo)->bind(function($val) {
return Identity::unit($val * 2);
});
echo $identity->get(); // 2
Maybe
<?php
use Monadic\Type\Maybe;
$foo = 1;
$maybe = Maybe::unit($foo)->bind(function($val) {
return Maybe::unit($val + 1);
});
echo $maybe->get(); // 2
$maybe = $maybe->bind(function($val) {
return Maybe::unit();
});
echo $maybe->get(); // null
Either
<?php
use Monadic\Type\Either\Right;
use Monadic\Type\Either\Left;
$foo = 1;
$either = Right::unit($foo)->bind(function($val) {
return Left::unit($val + 1);
})->left(function($val) {
return Right::unit($val + 1);
})->left(function($val) {
// not executed
return Right::unit($val + 1);
});
echo $either->get(); // 3
ListLike
ListLike代表列表类型(类)。因为列表是PHP中的保留字,所以这个类型被称为ListLike。
<?php
use Monadic\Type\ListLike;
$listLike = ListLike::unit(1,2,3);
$listLike = $listLike->bind(function($val) {
return ListLike::unit($val * 2);
});
echo $listLike[0]; // 3
echo $listLike[1]; // 4
echo $listLike[2]; // 6