Created
January 15, 2012 03:13
-
-
Save masakielastic/1614111 to your computer and use it in GitHub Desktop.
PHP で reduce と reduceRight
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 | |
// Haskell の foldl と foldr で同じ値の計算: http://blog.sarabande.jp/post/13599950587 | |
function reduce(array $input, $callable, $initial = NULL) { | |
$ret = $initial; | |
foreach ($input as $v) { | |
$ret = call_user_func($callable, $ret, $v); | |
} | |
return $ret; | |
} | |
function reduceRight(array $input, $callable, $initial = NULL) { | |
$ret = $initial; | |
foreach (array_reverse($input) as $v) { | |
$ret = call_user_func($callable, $v, $ret); | |
} | |
return $ret; | |
} | |
function f($x, $y) { | |
return $x + 2 * $y; | |
} | |
$array = array(1, 2, 3); | |
var_dump( | |
reduce($array, 'f', 4), // 16 | |
reduceRight($array, 'f', 4), // 49 | |
f(f(f(4, 1), 2), 3), // 16 | |
f(1, f(2, f(3, 4))) // 49 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment