Created
June 3, 2015 14:32
-
-
Save haskellcamargo/17580cf0c2dae96e9a1f to your computer and use it in GitHub Desktop.
Possible RFC - Piping operator
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
/** | |
* The piping operator (|>) is based on F# and LiveScript programming languages | |
* or (|) on Shell and allows you to compose functions in a stack and has | |
* left-associativity with lower precedence. | |
*/ | |
function map(callable $fn, array $xs) { | |
$acc = []; | |
foreach ($xs as $x) { | |
$acc[] = $fn($xs); | |
} | |
return $acc; | |
} | |
function filter(callable $fn, array $xs) { | |
$pass = []; | |
foreach ($xs as $x) { | |
if ($fn($x)) { | |
$pass[] = $x; | |
} | |
} | |
return $pass; | |
} | |
function even($x) { | |
return $x %% 2 === 0; | |
} | |
// With piping: | |
range(1, 10) | |
|> map (function($x) { return $x * 2 }) // => [1, 2, 3, 4 ... 20] | |
|> filter ('even'); // => [2,4,6,8,10,12,14,16,18,20] | |
// Without: | |
filter("even", | |
map(function($x) { return $x * 2; }, | |
range(1, 10))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment