Last active
October 19, 2017 14:47
-
-
Save ircmaxell/5320774 to your computer and use it in GitHub Desktop.
Monads - PHP
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 | |
class CollectionMonad extends Monad { | |
public function __construct(array $value) { | |
$this->value = $value; | |
} | |
public function bind($callback) { | |
$newValues = array(); | |
foreach ($this->value as $value) { | |
$newValues[] = $this->callCallback($callback, $value); | |
} | |
return new CollectionMonad($newValues); | |
} | |
} |
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 | |
class ErrorMonad extends Monad { | |
protected $value; | |
protected $error; | |
public function __construct($value, $error) { | |
$this->value = $value; | |
$this->error = $error; | |
} | |
public function bind($callback) { | |
$class = get_class($this); | |
try { | |
if (!$this->error) { | |
return new $class($this->callCallback($callback, $this->value)); | |
} | |
return new $class($this->value, $this->error); | |
} catch (\Exception $e) { | |
return new $class($this->value, $e->getMessage()); | |
} | |
} | |
} |
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 | |
class MaybeMonad extends Monad { | |
public function bind($callback) { | |
if ($this->value) { | |
return parent::bind($callback); | |
} | |
return new self(null); | |
} | |
} |
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 | |
class Monad { | |
protected $value; | |
public function __construct($value) { | |
$this->value = $value; | |
} | |
public function bind($callback) { | |
$class = get_class($this); | |
return new $class($this->callCallback($callback, $this->value)); | |
} | |
protected function callCallback($callback, $value) { | |
if ($value instanceof Monad) { | |
return $value->bind($callback); | |
} | |
return $callback($value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment