Skip to content

Instantly share code, notes, and snippets.

@andyhd
Created July 2, 2012 14:30
Show Gist options
  • Save andyhd/3033529 to your computer and use it in GitHub Desktop.
Save andyhd/3033529 to your computer and use it in GitHub Desktop.
Pseudo Maybe monad in PHP, for the lulz
<?php
/**
* A Maybe Monad class, encapsulates null checking
*/
class Maybe {
private $value;
public function __construct($value=null) {
$this->value = $value;
}
public function isEmpty() {
return is_null($this->value);
}
public function nonEmpty() {
return !$this->isEmpty();
}
public function map($fn) {
if ($this->isEmpty()) {
return $this;
} else {
return new Maybe($fn($this->value));
}
}
public function getOrElse($default) {
if ($this->isEmpty()) {
return $default;
}
return $this->value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment