Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Created January 15, 2012 03:13
Show Gist options
  • Save masakielastic/1614111 to your computer and use it in GitHub Desktop.
Save masakielastic/1614111 to your computer and use it in GitHub Desktop.
PHP で reduce と reduceRight
<?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