Last active
September 21, 2015 12:22
-
-
Save programaths/4e1497e82c1f4dae44c1 to your computer and use it in GitHub Desktop.
PHP generators
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 | |
// Data on which we operate | |
$tree=[ | |
'+'=>[ | |
'*'=>[1,2], | |
'-'=>[ | |
'+' => [3,4] | |
, 5 | |
] | |
] | |
]; | |
// Implementation using corroutines | |
function iterateTreeLeafs($tree) | |
{ | |
if(is_array($tree)){ | |
foreach($tree as $child){ | |
$subs=iterateTreeLeafs($child); | |
foreach($subs as $sub){ | |
yield $sub; | |
} | |
} | |
}else{ | |
yield $tree; | |
} | |
} | |
// Implementation using Iterators | |
class ExprIterator implements Iterator | |
{ | |
private $stack=[]; | |
private $current; | |
private $valid=true; | |
public function __construct($data) | |
{ | |
array_push($this->stack,$data); | |
} | |
public function current() | |
{ | |
return $this->current; | |
} | |
public function next() | |
{ | |
$this->valid=!empty($this->stack); | |
$item = array_pop($this->stack); | |
if(is_array($item)){ | |
while(is_array($item)) { | |
$item=array_reverse($item); | |
foreach($item as $i){ | |
array_push($this->stack,$i); | |
} | |
$item = array_pop($this->stack); | |
} | |
} | |
$this->current=$item; | |
} | |
public function key() | |
{ | |
return null; | |
} | |
public function valid() | |
{ | |
return $this->valid; | |
} | |
public function rewind() | |
{ | |
} | |
} | |
// Usage of both implementation | |
$generator=iterateTreeLeafs($tree); | |
foreach($generator as $leaf) | |
{ | |
echo $leaf; | |
} | |
$iterator=new ExprIterator($tree); | |
foreach($iterator as $leaf) | |
{ | |
echo $leaf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment