Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.