Last active
May 15, 2022 19:06
-
-
Save azerum/361b11bc3c96103c5fc37e4984575f63 to your computer and use it in GitHub Desktop.
Functions for partial application in 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 | |
| function bind(callable $f, ...$params) | |
| { | |
| return function () use ($f, $params) { | |
| return call_user_func_array($f, $params); | |
| }; | |
| } | |
| function partial(callable $f, ...$params) | |
| { | |
| $params_needed = (new ReflectionFunction($f))->getNumberOfParameters(); | |
| return _partial_recursive($f, $params, $params_needed); | |
| } | |
| function _partial_recursive(callable $f, array $passed_params, int $params_needed) | |
| { | |
| if (count($passed_params) >= $params_needed) { | |
| return call_user_func_array($f, $passed_params); | |
| } | |
| return function (...$params) use ($f, $passed_params, $params_needed) { | |
| return _partial_recursive( | |
| $f, | |
| array_merge($passed_params, $params), | |
| $params_needed | |
| ); | |
| }; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do not modify $passed_params array, because after its modification in closure partial function becomes unusable (array is already modified and function holds reference to it)