Skip to content

Instantly share code, notes, and snippets.

@auxiliaire
Created April 9, 2021 13:37
Show Gist options
  • Select an option

  • Save auxiliaire/040e30d4656a7c74fb36e32586a5f282 to your computer and use it in GitHub Desktop.

Select an option

Save auxiliaire/040e30d4656a7c74fb36e32586a5f282 to your computer and use it in GitHub Desktop.
Maybe in PHP
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