Guest User

Untitled

a guest
Nov 20th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. <?php
  2. /**
  3. * A Maybe Monad class, encapsulates null checking
  4. */
  5. class Maybe {
  6.  
  7. private $value;
  8.  
  9. public function __construct($value=null) {
  10. $this->value = $value;
  11. }
  12.  
  13. public function isEmpty() {
  14. return is_null($this->value);
  15. }
  16.  
  17. public function nonEmpty() {
  18. return !$this->isEmpty();
  19. }
  20.  
  21. public function map($fn) {
  22. if ($this->isEmpty()) {
  23. return $this;
  24. } else {
  25. return new Maybe($fn($this->value));
  26. }
  27. }
  28.  
  29. public function getOrElse($default) {
  30. if ($this->isEmpty()) {
  31. return $default;
  32. }
  33. return $this->value;
  34. }
  35.  
  36. }
Add Comment
Please, Sign In to add comment