PHP ruby ​​inject () behavior emulation

From this question here , I wrote an enum wrapper to have some methods that can be used with lambdas to emulate several ruby ​​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 efficiently as possible ?


EDIT: The method is implemented as shown above. Examples of using:

// 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; } 
    ); 
+3
source share
1 answer

I am not familiar with Ruby, but from the description it is similar to array_reduce.

mixed array_reduce ( array $input , callback $function [, mixed $initial = NULL ] )

array_reduce() an iteratively functional function is applied to the input elements of the array to reduce the array to a single value.

"" "fold" ; Mathematica:

Fold[f, init, {a, b, c, d}] == f[f[f[f[init, a], b], c], d]

( ).

:

//$arr is the initial array
$first = array_shift($arr);
$result = array_reduce($arr, $callback, $first);

PHP , , .

:

  • array_reduce. , . ( ).
  • , toArray, array_reduce. .
  • array_reduce, Traversable. , Traversable , . ArrayIterator .
+5

Source: https://habr.com/ru/post/1756426/


All Articles