Last active
December 25, 2017 23:51
-
-
Save sergiors/79601098e2b09a1d90c0814c8a1fb6e5 to your computer and use it in GitHub Desktop.
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 | |
// [a] -> a | |
function head(array $list) | |
{ | |
return array_slice($list, 0, 1)[0]; | |
} | |
// [a] -> a | |
function last(array $list) | |
{ | |
return array_slice($list, -1)[0]; | |
} | |
// [a] -> [a] | |
function tail(array $list) | |
{ | |
return array_slice($list, 1); | |
} | |
// [a] -> [a] | |
function init(array $list) | |
{ | |
return array_slice($list, 0, -1); | |
} | |
// Foldable t => (b -> a -> b) -> b -> t a -> b | |
function foldl(callable $func, array $list, $initval) | |
{ | |
return [] === $list | |
? $initval | |
: $func( | |
foldl($func, init($list), $initval), | |
last($list) | |
); | |
} | |
// (a -> b) -> [a] -> [b] | |
function map(callable $func, array $list): array | |
{ | |
return foldl(function (array $list, $n) use ($func) { | |
return array_merge($list, [ | |
$func($n) | |
]); | |
}, $list, []); | |
} | |
var_dump( | |
map( | |
function (int $x): int { | |
return $x + 10; | |
}, | |
[10, 20, 30] | |
) | |
); | |
var_dump( | |
foldl( | |
function (int $x, int $y): int { | |
return $x + $y; | |
}, | |
[5, 10, 20], | |
0 | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment