Last active
December 25, 2015 16:19
-
-
Save gotohr/7005203 to your computer and use it in GitHub Desktop.
declarative function composition - PHP
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 | |
use \Closure; | |
class Invokable { | |
private $closure; | |
public function __construct(Closure $closure) { | |
$this->closure = $closure; | |
} | |
public static function newInstance(Closure $closure) { | |
return new self($closure); | |
} | |
public function __invoke($arg) { | |
$c = $this->closure; | |
return $c($arg); | |
} | |
public function compose(Invokable $inner) { | |
$inv = $this; | |
return Invokable::newInstance( | |
function($i) use ($inv, $inner) { | |
return $inv($inner($i)); | |
} | |
); | |
return $this; | |
} | |
} | |
$inv1 = Invokable::newInstance( | |
function($i) { | |
return $i * 2; | |
} | |
); | |
$inv2 = Invokable::newInstance( | |
function($i) { | |
return $i + 1; | |
} | |
); | |
$inv3 = Invokable::newInstance( | |
function($i) { | |
return $i + 10; | |
} | |
); | |
$inv = $inv1->compose($inv2)->compose($inv3); | |
echo ($inv(2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment