Last active
March 9, 2020 05:43
-
-
Save igorw/7808019 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 | |
// iterator impl: | |
class MapIterator extends IteratorIterator { | |
private $f; | |
public function __construct($f, $inner) { | |
parent::__construct($inner); | |
$this->f = $f; | |
} | |
function current() { | |
return call_user_func($this->f, parent::current()); | |
} | |
} | |
function iter_map($f, $iter) { | |
return new MapIterator($f, $iter); | |
} | |
// generator impl: | |
function gen_map($f, $iter) { | |
foreach ($iter as $k => $v) { | |
yield $k => $f($v); | |
} | |
} | |
// example: | |
function times_two($x) { | |
return $x * 2; | |
} | |
$source = new ArrayIterator([0, 1, 2, 3, 4, 5, 6]); | |
var_dump(iterator_to_array(iter_map('times_two', $source))); | |
var_dump(iterator_to_array(gen_map('times_two', $source))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment