Created
April 9, 2021 13:37
-
-
Save auxiliaire/040e30d4656a7c74fb36e32586a5f282 to your computer and use it in GitHub Desktop.
Maybe in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Maybe { | |
| public function __construct(private $value = null) { } | |
| public function isNothing(): bool { | |
| return $this->value === null; | |
| } | |
| public function isJust(): bool { | |
| return !$this->isNothing(); | |
| } | |
| public function __toString() { | |
| return $this->isNothing() ? 'Nothing' : "Just(" . var_export($this->value, true) . ")"; | |
| } | |
| public function get() { | |
| return $this->value; | |
| } | |
| // Pointed Maybe | |
| public static function of($x = null) { | |
| return new Maybe($x); | |
| } | |
| // Functor Maybe | |
| public function map(callable $fn): Maybe { | |
| return $this->isNothing() ? $this : Maybe::of($fn($this->value)); | |
| } | |
| // TODO: add more functional methods here | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment