Skip to content

Instantly share code, notes, and snippets.

@copperwall
Created May 22, 2017 00:27
Show Gist options
  • Save copperwall/95fc33731dc614d2da9a9b8448dca71b to your computer and use it in GitHub Desktop.
Save copperwall/95fc33731dc614d2da9a9b8448dca71b to your computer and use it in GitHub Desktop.
<?php
function lazy_map(callable $f, Iterator $list): Iterator {
foreach ($list as $item)
yield $f($item);
}
function lazy_filter(callable $f, Iterator $list): Iterator {
foreach ($list as $item)
if ($f($item))
yield $item;
}
function tiny_gen(): Iterator {
foreach (range(1, 10) as $num)
yield $num;
}
$addOne = function($item) { return $item + 1; };
$isOdd = function($item) { return $item % 2; };
// Using lazy functions
$odds = lazy_filter($isOdd, lazy_map($addOne, tiny_gen()));
// 3
// 5
// 7
// 9
// 11
foreach ($odds as $odd) {
echo "$odd\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment