Generator (iterator protocol based)
- Intent
- Define a (stream like) value producer
- Motivation
- We want to be able do define functional streams
- Implementation
- Any object implementing an iteration protocol (interface) can be a base for a generator.
- Examples
//a generator implemented with iterators
function generator($it=null, $cb=null) {
static $itor;
static $callback;
if(!isset($itor)) ($itor = $it; $callback=$cb; }
if($valid()) { $out = $callback($current); $next(); return $out; }
//or if you are not sure about the type of the above callables ($valid, $next,..)
if( call_user_func($valid) ) {
$out = call_user_func( $callback, $current);
call_user_func( $next );
return $out;
}
else throw( new some_exception );
}