Created
July 2, 2012 14:30
-
-
Save andyhd/3033529 to your computer and use it in GitHub Desktop.
Pseudo Maybe monad in PHP, for the lulz
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 | |
/** | |
* 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