Created
May 22, 2017 00:27
-
-
Save copperwall/95fc33731dc614d2da9a9b8448dca71b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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