Check out Dart's iterators

David Bruant bruant.d at gmail.com
Sun Feb 10 07:21:35 PST 2013


Le 10/02/2013 13:21, Alex Russell a écrit :
>
> FWIW, there continue to be strong misgivings about the pythonesqe 
> design we have now, but Mozilla insists on the back of their shipping 
> implementation. Many feel that exceptions for control-flow are a 
> missdesign, myself included
>
I agree and also think return-true/false protocols aren't any better. In 
an ideal world,
<idealworld>
an extensible way to end a frame would be better for this kind of 
function-based protocols.

     function(){
         if(last())
             return next();
         else
             throw StopIteration;
     }

     // would become

     function(){
         if(last())
             return next();
         else
             endframe as StopIteration
     }

Return and throw would be mere sugar for "endframe as return(value)" and 
"endframe untilcaught as throw(value)". untilcaught would indicate that 
this termination value propagates until being try-caught (though in my 
ideal world, there would be no throw, because I find it too agressive)
What I'm describing here is nothing more than a generic mechanism to 
create new completion value types. I actually find fascinating that the 
SpiderMonkey debugger API completion value documentation [1] has a 
specific note to explain how to recognize the end of an iterator frame.

In this ideal world, the iterator consumer story would be as follow:
     // ES6 snippet:
     try{
         var value = it.next();
         // code to manipulate the value
     }
     catch(e){
         if(e instanceof StopIteration){
             // code to run when out of elements
         }
     }

     // would become:
     var complValue = completion it.next()
     if(complValue.type === 'return'){
         // code playing with complValue.return;
     }
     if(complValue.type === 'StopIteration'){
         // code to run when out of elements
     }
     // or something that looks more legit than the try/catch thing

The proposed "throw ForwardToTarget" would be nothing less than 
"endframe as ForwardToTarget" in this world.

In this ideal world, function protocols are based not on *what* a 
function released (return/throw value), but rather on *how* the function 
ended.
</idealworld>

But we do not live in the "endframe as"+"completion" world. "throw 
StopIteration" is probably as close as we can get in JavaScript given 
the 3 way to complete a frame that we have (return/throw/yield). If 
anything, it's very explicit about what it does ("stop iteration"). More 
than a return true/false protocol.

Maybe Dart could consider something like "endframe as"+"completion" 
though...

David

[1] 
https://developer.mozilla.org/en-US/docs/SpiderMonkey/JS_Debugger_API_Reference/Completion_values


More information about the es-discuss mailing list