5 ms·
One reason I wish JS had goto
- deleted 17y ago[deleted]
- jacquesm 17y agotypedef struct State { int state; int num; } State; int f(State* state, int n) { if (state->state == 0) { // initial call state->num = 0; if (state->num <= n) { state->state = 1; return state->num; } } if (state->num < n) { state->num++; return state->num; } return -1; } And technically you're using 'state' as though it is initialized to '0' anyway, so you might as well do the same for 'num' that changes the code to: int f(State* state, int n) { if (state->num < n) { return state->num++; } return -1; } Or am I missing something ? edit: that's what you get for coding before morning tea ;) edit2: shortened first code a bit further edit3: In javascript this is the closest that I can get to your python example: <script languge='JavaScript'> function f(s,limit) { if (typeof s.num == 'undefined') { s.num = 0; } if (s.num < limit || (s.num == 0 && limit ==0)) { return s.num++; } return -1; } g = {}; while ((t=f(g,10)) != -1) { document.writeln(t + "\n"); } </script> So that's one line extra to declare the variable holding the state for the generator. The 'undefined' trick is pretty gory, but it does do away with the 'location' variable or a need to initialize it. I take it that this does not generalize to your use case though, it is just a 'special case' solution for the python sample you gave, do you have a more complicated sample for a generator that would fail using this simplistic scheme ? Interesting thing you have on the go there, if you succeed in making a fully compatible in the browser version of python I think a lot of folks will be really happy, it would be the ideal learning tool, especially if it would have access to a canvas to draw on. That would be a really nice environment for kids to learn how to program.
- apgwoz 17y agoThis is the type of thing you don't need goto for, if you have first class continuations, or properly optimized tail recursion. Continuations would allow you to write your own control structures in much the same way.
- didroe 17y agoGiven the Python example in the article: def f(n): num = 0 while num < n: yield num num += 1 what's wrong with: function f(n) { var num = 0; return function () { if (num < n) { return num++; } } }
- _ck_ 17y agoYeah but then you'd have to deal with raptor attacks http://xkcd.com/292 http://xkcd.com/292