Created
August 3, 2017 14:33
-
-
Save travis-bradbury/dcd12978a269fc63da7cd10550730d9f to your computer and use it in GitHub Desktop.
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
| <?php | |
| function ok($value) { | |
| return new Result('ok', $val); | |
| } | |
| function err($value) { | |
| return new Result('err', $val); | |
| } | |
| class Result { | |
| protected $value; | |
| protected $type; | |
| protected $is_err; | |
| public function __construct($type = 'ok', $value) { | |
| $this->type = $type; | |
| $this->value = $value; | |
| } | |
| public static function newOk($val) { | |
| return new static('ok', $val); | |
| } | |
| public static function newErr($val) { | |
| return new static('err', $val); | |
| } | |
| public function isErr() { | |
| return $this->type !== 'ok'; | |
| } | |
| public function ok() { | |
| return $this->isErr() ? NULL : $this->value(); | |
| } | |
| public function err() { | |
| return $this->isErr() ? $this->value() : NULL; | |
| } | |
| public function or_else($callable) { | |
| if ($this->isErr()) { | |
| return $callable(); | |
| } | |
| return $this->value; | |
| } | |
| public function map($callable) { | |
| if (!$this->isErr()) { | |
| return $callable($this->value()); | |
| } | |
| return $this->value(); | |
| } | |
| public function map_err($callable) { | |
| if ($this->isErr()) { | |
| return $callable($this->value()); | |
| } | |
| return $this->value(); | |
| } | |
| public function and_then($callable) { | |
| if ($this->isErr()) { | |
| } | |
| return $callable($this->value()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment