'function *' is not mandatory

François REMY francois.remy.dev at outlook.com
Wed Sep 4 10:01:30 PDT 2013


> It sounds like you are saying that generators are too high-level, and
> it would be better to expose a lower-level primitive.
>
> But what would that lower-level primitive be? What operations would it expose?

State machines. As you can see for your Traceur example, there are two things here: the state machine function, and the Iterator wrapper. I propose ES6 ships a wrapper (Iterator) and a syntaxic sugar (yield) to make creating state machines easier.


For example, having the yield logic independant of the Iterator wrapper could allow creative usages like:

    function DeterministicSolutionFinder(func, valuesToTry) {
        let queue = [func]; while(queue.length !== 0) {
            let current = queue.shift();
            for(let value of valuesToTry) {
                
                let currentResult = current(value);
                if (!currentResult) {
                    continue
                    
                } else if(!(currentResult instanceof YieldReturn)) { 
                    return currentResult
                    
                } else if(!(currentResult.done)) { 
                    queue.push(currentResult.next) 
                    
                }
                
            }
        }
    }
    
    DeterministicSolutionFinder(=>{
       
       var x = [ yield, yield, yield, yield ];
        if( (x[0]||x[1]) && (!x[1]||!x[2]) && ...) { return x; }
       
    },[true,false])

I hereby used the underlying behavior of "yield" to create a basic fork() in the special case of functionnal-programming-compatible functions (ie: variables are defined only once and previously defined variables are not modified during the function execution to prevent side-effects on further executions).

You simply cannot do the same thing if you've to restrict yourself to the Iterator wrapper.




> How is any of this different from generators?
>
> http://goo.gl/Flf2ru

The difference is that you could use the "ES5 version" with the native Iterator wrapper, you're not forced to build your own if the browser already ship an Iterator wrapper (it could just be a polyfill for older browsers).

The other difference is that there's no "implied yield" at the beginning of the function. Yield is a special kind of return, but the fact a function contains a yield doesn't suddenly change its behavior completely.

You're also free to choose whichever wrapper implementation fits your needs, which is kinda great. 		 	   		  


More information about the es-discuss mailing list