Skip to content

Instantly share code, notes, and snippets.

@assertchris
Last active June 30, 2016 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save assertchris/6dd66348650bf3a469cea07f5a0b2ece to your computer and use it in GitHub Desktop.
Save assertchris/6dd66348650bf3a469cea07f5a0b2ece to your computer and use it in GitHub Desktop.
<?php
function is_iterable($value) {
return is_array($value) || $value instanceof Traversable;
}
function flatMap(/* iterable */ $iterable, callable $callable) {
foreach ($iterable as $value) {
if (is_iterable($value)) {
foreach (flatMap($value, $callable) as $next) {
yield $next;
}
} else {
yield $callable($value);
}
}
}
$callable = function($value) {
print "value: {$value}\n";
return $value * 2;
};
$one = [1, 2, 3];
print_r(
iterator_to_array(
flatMap($one, $callable)
)
);
$two = [1, [2, 3], 4];
print_r(
iterator_to_array(
flatMap($two, $callable)
)
);
$three = [1, [2, 3, new ArrayIterator([4])], 5];
print_r(
iterator_to_array(
flatMap($three, $callable)
)
);
@frankdejonge
Copy link

frankdejonge commented Jun 29, 2016

function flatMap(/* iterable */ $iterable, callable $callable) {
    foreach ($iterable as $value) {
        if (is_iterable($value)) {
            yield from flatMap($value, $callable);
        } else {
            yield $callable($value);
        }
    }
}

@assertchris
Copy link
Author

Unfortunately that gives different (and undesired output). It was what I initially thought should work in this situation, but alas not...

@trowski
Copy link

trowski commented Jun 29, 2016

iterator_to_array() preserves keys by default. Using iterator_to_array(flatMap(...), false) works as expected. yield from results in duplicate keys.

@assertchris
Copy link
Author

Thanks for the tip. In that case, I definitely prefer not to use yield from. I don't think the relatively small performance hit is worth the caveat of duplicate indices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment