Skip to content

Instantly share code, notes, and snippets.

@igorw
Last active March 9, 2020 05:43
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save igorw/7808019 to your computer and use it in GitHub Desktop.
Save igorw/7808019 to your computer and use it in GitHub Desktop.
<?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