Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created June 30, 2019 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikoheikkila/a925830cb0bd0944495a79522b7564c3 to your computer and use it in GitHub Desktop.
Save nikoheikkila/a925830cb0bd0944495a79522b7564c3 to your computer and use it in GitHub Desktop.
Functional Piping in PHP
<?php declare(strict_types = 1);
function pipe(...$args) {
return function ($arg) use ($args) {
$reducer = function ($prev, $fn) {
return $fn($prev);
};
return array_reduce($args, $reducer, $arg);
};
}
function pipeWith($arg, ...$fns) {
return pipe(...$fns)($arg);
}
$odds = function (array $a): array {
return array_filter($a, function ($x) {
return $x % 2 !== 0;
});
};
$double = function (array $a): array
{
return array_map(function ($x) {
return $x * 2;
}, $a);
};
$log = function (array $a): array {
echo implode(', ', $a);
return $a;
};
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// These are functionally same and print out '2, 6, 10, 14, 18'
pipe($odds, $double, $log)($data);
pipeWith($data, $odds, $double, $log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment