Created
June 30, 2019 11:48
-
-
Save nikoheikkila/a925830cb0bd0944495a79522b7564c3 to your computer and use it in GitHub Desktop.
Functional Piping in 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 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