Skip to content

Instantly share code, notes, and snippets.

@igorw
Last active August 23, 2021 16:47
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorw/5899819 to your computer and use it in GitHub Desktop.
Save igorw/5899819 to your computer and use it in GitHub Desktop.
Lazy sequences using PHP 5.5 generators.
<?php
// thanks to metaultralurker on reddit for inspiration
function map(callable $fn, \Traversable $data) {
foreach ($data as $v) {
yield $fn($v);
}
}
function filter(callable $fn, \Traversable $data) {
foreach ($data as $v) {
if ($fn($v)) {
yield $v;
}
}
}
function infinite_range() {
$i = 0;
while (true) {
yield $i++;
}
}
function take($n, \Traversable $data) {
$i = 0;
foreach ($data as $v) {
if ($i++ === $n) {
break;
}
yield $v;
}
}
function reduce(callable $fn, \Traversable $data, $runningTotal = null) {
$first = true;
foreach ($data as $v) {
if (null === $runningTotal && $first) {
$runningTotal = $v;
continue;
}
$runningTotal = $fn($runningTotal, $v);
$first = false;
}
return $runningTotal;
}
$isEven = function ($x) {
return $x % 2 == 0;
};
$data = take(10, map('floatval', filter($isEven, infinite_range())));
/*
var_dump($data->current());
$data->next();
var_dump($data->current());
$data->next();
*/
// var_dump(iterator_to_array($data));
$concat = function ($sep, $a, $b) {
return $a.$sep.$b;
};
$concatComma = function ($a, $b) use ($concat) {
return $concat(',', $a, $b);
};
var_dump(reduce($concatComma, $data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment