Skip to content

Instantly share code, notes, and snippets.

@travis-bradbury
Created August 3, 2017 14:33
Show Gist options
  • Select an option

  • Save travis-bradbury/dcd12978a269fc63da7cd10550730d9f to your computer and use it in GitHub Desktop.

Select an option

Save travis-bradbury/dcd12978a269fc63da7cd10550730d9f to your computer and use it in GitHub Desktop.
<?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