Skip to content

Instantly share code, notes, and snippets.

@cystbear
Last active January 31, 2020 19:12
Show Gist options
  • Save cystbear/ec672c5bf7f2fa5b6197 to your computer and use it in GitHub Desktop.
Save cystbear/ec672c5bf7f2fa5b6197 to your computer and use it in GitHub Desktop.
My PHP Currying implementation
<?php
function curry(\Closure $f) {
$rf = new \ReflectionFunction($f);
$arity = $rf->getNumberOfParameters();
function acc($f, $arity, $args=[]) {
return function(...$acc) use($f, $arity, $args) {
$acc = array_merge($args, $acc);
return (count($acc) >= $arity) ? $f(...$acc) : acc($f, $arity, $acc);
};
};
return acc($f, $arity);
};
// ==================================================
$sum_func = function($a,$b,$c) {
return $a+$b+$c;
};
$cur = curry($sum_func);
var_dump($cur(1,2,3));
var_dump($cur(1,2)(3));
var_dump($cur(1)(2)(3));
var_dump($cur()(1)()(2)()(3));
var_dump($cur()()()()(1)()(2)()(3,4,5));
<?php
function runner(\Closure $generator, $ctx, \Closure $printer = null, \Closure $interruptor = null) {
if ($interruptor) if ($interruptor(...$ctx)) return;
if ($printer) $printer(...$ctx);
yield from runner($generator, $generator(...$ctx), $printer, $interruptor);
};
$printer = function($n){ob_start(); print $n.PHP_EOL.PHP_EOL; ob_end_flush();};
$interruptor = function($n){return $n >= PHP_INT_MAX;};
$fib = function($k){return ['gen'=>function($a, $b){return [$b, $a+$b];}, 'ctx'=>[1,1]][$k];};
// $fc = function($k){return ['gen'=>function($a, $b){return [$a*$b, ++$b];}, 'ctx'=>[1,1]][$k];};
runner($fib('gen'), $fib('ctx'), $printer, $interruptor)->current();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment