0

I'm trying to adapt this code:

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        echo implode($perms); // yield (implode($perms));
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

To a yield, as you see commented in the same line. But doing so returns no values.

I'm calling it with:

  foreach (pc_permute($a) as $y) {
        echo $y;
  }

Where $a should be something like $a = [0,1,2];

With echo works and with yield does not. What am I doing wrong?

Cristo
  • 700
  • 1
  • 8
  • 20
  • So i'm yielding to a recursive function, which is returning nothing. How would I escalate that to grandparent's function? ` yield pc_permute($newitems, $newperms); yield (implode($perms)); ` Something like that returns generator objects ad infinitum – Cristo Jun 04 '16 at 12:18
  • I did the trick in another part with something like: array_push($this->permutations, $perms); instead of the yield, but I would like a better way, like directly retrieve the yield – Cristo Jun 04 '16 at 12:22
  • 1
    python has `yield from`, if there's nothing similar, write a loop. – Karoly Horvath Jun 04 '16 at 12:24
  • yield from pc_permute($newitems, $newperms); was it! Thanks a lot. Would you answer ? – Cristo Jun 04 '16 at 12:28

1 Answers1

0

Your recursive call ignores the yielded values.

Since PHP 7 you can use generator delegation (yield from):

yield from pc_permute($newitems, $newperms);

With older versions just write a loop that yields each result.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176