Created
December 1, 2016 20:02
-
-
Save twslade/fb1319bb424591643084dceead4bec16 to your computer and use it in GitHub Desktop.
This file contains 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 Only{ | |
protected $_container = null; | |
public function __construct($value){ | |
$this->_container = $value; | |
} | |
public function get(){ | |
return $this->_container; | |
} | |
public static function pack($value){ | |
return new static($value); | |
} | |
public function map($func){ | |
return $func($this->_container); | |
} | |
} | |
//First Law: Left Identity | |
//Result of function applied to value | |
//should be the same as wrapped value being applied | |
//to value | |
$addTwo = function($value){return $value + 2;}; | |
var_dump($addTwo(2) == Only::pack(2)->map($addTwo)); | |
//Second Law: Right Identity | |
//Passing in a function that does not operate on | |
//supplied value, but only calls pack() must return | |
//same value as what is bound in monad ie 2 | |
$only = Only::pack(2); | |
$only_applied = $only->map(function($value){ | |
return Only::pack($value); | |
}); | |
var_dump($only->get() === $only_applied->get()); | |
//Third Law: Nesting map() calls must produce the same | |
//result as when they are called subsequentially | |
$addTwo = function($value){return Only::pack($value + 2);}; | |
$subtractTwo = function($value){return Only::pack($value - 2);}; | |
$only = Only::pack(2)->map($addTwo)->map($subtractTwo); | |
$onlyDirr = Only::pack(2)->map(function($value) use ($addTwo, $subtractTwo){ | |
return $addTwo($value)->map(function($value)use($subtractTwo){ | |
return $subtractTwo($value); | |
}); | |
}); | |
var_dump($only->get() === $onlyDirr->get()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment