Functional Programming in PHP: Part 5

bingo-functional artwork
<?phpfunction throwSomeException()
{
throw new Exception('I am an exception');
}
function addFunction(int $operand)
{
$otherOperand = throwSomeException();
try {
$result = $operand + $otherOperand;
} catch (Exception $excpetion) {
$result = 30;
}
return $result;
}
addFunction(12);
//prints a PHP Warning
//the warning cannot be substituted with the intended result
//referential transparency red flag
<?phpuse Chemem\Bingo\Functional\Functors\{Either\Either, Maybe\Maybe};$number = Maybe::fromValue(12);$finalValue = $number
->filter(
function (int $number) : int {
return $number > 5;
}
)
->map(
function (int $number) : int {
return $number * 4;
}
);
var_dump($finalValue); //outputs 48 wrapped in Maybe\Just object
$number = Either::right(12);$finalValue = $number
->filter(
function (int $number) : int {
return $number > 5;
},
24 //arbitrary error value
)
->map(
function (int $number) : int {
return $number * 4;
}
);
var_dump($finalValue);
//outputs 48 wrapped in an Either\Right object
function add(int $x, int $y) : int
{
return $x + $y;
}
$maybeLifted = Maybe::lift('add');
$eitherLifted = Maybe::lift('add');
$maybeResult = $maybeLifted(
Maybe::fromValue(2),
Maybe::fromValue(3)
);
$eitherResult = $eitherLifted(
Either::right(2),
Either::right(3)
);
$maybeResult->flatMap('var_dump'); //outputs 5
$eitherResult->flatMap('var_dump'); //also outputs 5

I write PHP and I know things — kind of. https://chemem.site