/** * concat * * Creates a lazily concatenated stream whose elements are all the elements * of the first stream followed by all the elements of the second stream. * * @param Stream $a * @param Stream $b * @return Stream */ public static function concat(S\Stream $a, S\Stream $b) { $items = $a->getElements() + $b->getElements(); return new S\Stream($items); }
require __DIR__ . "/src/Producer/Producer.php"; require __DIR__ . "/src/Producer/CallableProducer.php"; $randProducer = function ($value) { for ($i = 0; $i < $value; $i++) { (yield mt_rand(0, ($i + 1) * 100)); } }; $numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; $numberformatter = function ($v) use($numbers) { $v = (string) $v; $str = []; for ($i = 0, $l = strlen($v); $i < $l; ++$i) { $str[] = $numbers[$v[$i]]; } return implode(" ", $str); }; $numbersReversed = array_flip($numbers); $numberReverseFormatter = function ($v) use($numbersReversed) { return $numbersReversed[$v]; }; $stuff = \Streams\Stream::from([1, 2, 3, 8, 5, 20, 131, 3425, 134])->flatMap($randProducer)->flatMap($randProducer)->filter(function ($v) { return !($v % 3) || !($v % 2); })->map($numberformatter)->flatMap(function ($formatted) { return explode(" ", $formatted); })->map($numberReverseFormatter)->skip(1000)->limit(200)->compile(); //echo $stuff->compile(), "\n\n"; //echo $stuff->reduce(function ($v, $acc) { return $v + $acc; }, 0), "\n"; foreach ($stuff as $formatted) { echo $formatted, "\n"; } echo memory_get_peak_usage() / 1024, "kb\n";
public function testLetsDoCoolThingsSuchAsMapReduce() { $arrayOfPhrases = array('first second third', 'first second', 'fourth second fourth', 'first second second', 'third second third'); $phrasesStream = new S\Stream($arrayOfPhrases); $computedArray = $phrasesStream->map(function ($line) { return array_count_values(explode(' ', $line)); })->reduce(array(), function ($acc, $next) { foreach ($next as $word => $count) { if (isset($acc[$word])) { $acc[$word] += $count; } else { $acc[$word] = $count; } } return $acc; }); $this->assertEquals(3, $computedArray['first']); $this->assertEquals(6, $computedArray['second']); $this->assertEquals(3, $computedArray['third']); $this->assertEquals(2, $computedArray['fourth']); }