Skip to content

Instantly share code, notes, and snippets.

@Crell
Created Jun 8, 2021
Embed
What would you like to do?
--TEST--
This is hot.
--FILE--
<?php
enum Num {
case NegativeNumber;
case ZeroUnsupported;
public static function wrap(callable $c): callable {
return fn(mixed $arg): mixed => $arg instanceof self ? $arg : $c($arg);
}
}
function add(int $a, int $b):int|Num {
if ($a < 0 || $b < 0) {
return Num::NegativeNumber;
}
return $a + $b;
}
function mult(int $a, int $b):int|Num {
if ($a < 0 || $b < 0) {
return Num::NegativeNumber;
}
return $a * $b;
}
function minus(int $a, int $b):int|Num {
if ($a < 0 || $b < 0) {
return Num::NegativeNumber;
}
return $a - $b;
}
function div(int $a, int $b):int|Num {
if ($a < 0 || $b < 0) {
return Num::NegativeNumber;
}
if ($b === 0) {
return Num::ZeroUnsupported;
}
return $a / $b;
}
$result = 5
|> Num::wrap(add(1, ?))
|> Num::wrap(mult(?, 4))
|> Num::wrap(div(?, 2));
print $result . PHP_EOL;
$result = 5
|> Num::wrap(add(1, ?))
|> Num::wrap(minus(?, 10))
|> Num::wrap(div(?, 2))
|> Num::wrap(mult(?, 3));
var_dump($result);
?>
--EXPECT--
12
enum(Num::NegativeNumber)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment