From this question here, I was writing an enum wrapper to have some methods that can be used with lambdas to somewhat emulate ruby's usage of blocks in enums.
class enum {
public $arr;
function __construct($array) {
$this->arr = $array;
}
function each($lambda) {
array_walk($this->arr, $lambda);
}
function find_all($lambda) {
return array_filter($this->arr, $lambda);
}
function inject($lambda, $initial=null) {
if ($initial == null) {
$first = array_shift($this->arr);
$result = array_reduce($this->arr, $lambda, $first);
array_unshift($this->arr, $first);
return $result;
} else {
return array_reduce($this->arr, $lambda, $initial);
}
}
}
$list = new enum(array(-1, 3, 4, 5, -7));
$list->each(function($a) { print $a . "\n";});
// in PHP you can also assign a closure to a variable
$pos = function($a) { return ($a < 0) ? false : true;};
$positives = $list->find_all($pos);
Now, how could I implement inject() as elegantly as possible?
EDIT: method implemented as seen above. Usage examples:
// inject() examples
$list = new enum(range(5, 10));
$sum = $list->inject(function($sum, $n) { return $sum+$n; });
$product = $list->inject(function($acc, $n) { return $acc*$n; }, 1);
$list = new enum(array('cat', 'sheep', 'bear'));
$longest = $list->inject(function($memo, $word) {
return (strlen($memo) > strlen($word)) ? $memo : $word; }
);