Created
November 29, 2016 23:07
-
-
Save twslade/4efba517d08ab1d68ca8060c2b57a310 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 | |
function compose($a, $b){ | |
return function() use ($a, $b){ | |
$args = func_get_args(); | |
return $b(call_user_func_array($a, $args)); | |
}; | |
} | |
class Just{ | |
protected $_value; | |
public function __construct($value){ | |
$this->set($value); | |
} | |
public function set($value){ | |
$this->_value = $value; | |
} | |
public function get(){ | |
return $this->_value; | |
} | |
public function __invoke($func){ | |
return new Just($func($this->_value)); | |
} | |
} | |
interface ApplicativeInterface{ | |
public function __invoke(); | |
} | |
class Applicative implements ApplicativeInterface{ | |
protected $_func; | |
public function __construct($func){ | |
$this->set($func); | |
} | |
public function set($func){ | |
$this->_func = $func; | |
} | |
public function get(){ | |
return $this->_func; | |
} | |
public function __invoke(){ | |
if(func_get_arg(0) instanceof ApplicativeInterface){ | |
$func = $this->get(); | |
foreach(func_get_args() as $arg){ | |
if($arg instanceof ApplicativeInterface){ | |
$func = compose($func, $arg->get()); | |
} | |
} | |
return new static($func); | |
} else { | |
return call_user_func_array($this->get(), func_get_args()); | |
} | |
} | |
} | |
function aMap($applicative){ | |
$funcName = __FUNCTION__; | |
$params = array_slice(func_get_args(), 1); | |
if(is_array($applicative)){ | |
return array_map(function($actualApplicative) use ($funcName, $params){ | |
array_unshift($params, $actualApplicative); | |
return call_user_func_array($funcName, $params); | |
}, $applicative); | |
} | |
if($applicative instanceof ApplicativeInterface){ | |
return call_user_func_array($applicative, $params); | |
} else { | |
throw new Exception('Must be called with Applicative'); | |
} | |
} | |
$plus1Func = function($value){return $value+1;}; | |
$plus3Func = function($value){return $value+3;}; | |
$plus10Func = function($value){return $value+10;}; | |
$pureF1 = new Applicative($plus1Func); | |
$pureF3 = new Applicative($plus3Func); | |
$pureF10 = new Applicative($plus10Func); | |
$result = amap($pureF1, $pureF3, $pureF10); | |
var_dump($result(1)); | |
var_dump(debug_backtrace()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment