Skip to content

Instantly share code, notes, and snippets.

@ircmaxell
Last active October 19, 2017 14:47
Show Gist options
  • Save ircmaxell/5320774 to your computer and use it in GitHub Desktop.
Save ircmaxell/5320774 to your computer and use it in GitHub Desktop.
Monads - PHP
<?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);
}
}
<?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());
}
}
}
<?php
class MaybeMonad extends Monad {
public function bind($callback) {
if ($this->value) {
return parent::bind($callback);
}
return new self(null);
}
}
<?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