I thought about how to express the yield of Python in Java and JavaScript.
This time, I didn't try to make something practical, but I thought about how to replace it if I made a code generator.
For the time being, I tried to use this as a subject.
http://ideone.com/PG6xOJ
# your code goes here
def Generator(n):
yield 1;
idx = 0
while idx < n:
yield 2
idx += 1
yield 3
g = Generator(5)
for x in g:
print x
A little thought policy
I wrote it in JavaScript with this policy.
http://ideone.com/24L64n
// your code goes here
function Generator(n) {
var ctx = { state:0, idx:0 };
return function() {
while (1) {
switch (ctx.state) {
case 0:
ctx.state = 1;
return 1;
case 1:
if (ctx.idx < n) {
ctx.idx++;
return 2;
}
ctx.state = 2;
break;
case 2:
ctx.state = -1;
return 3;
default:
return undefined;
}
}
};
}
(function() {
var g = Generator(5);
while (1) {
var x = g();
if (x === undefined)
break;
print(x);
}
})();
I wrote it in Java as well.
http://ideone.com/YnxHkv
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
private static class Generator {
final int n_;
int state_ = 0, idx_ = 0;
boolean completed_ = false;
Generator(int n) {
n_ = n;
}
int generate() {
while (true) switch (state_) {
case 0:
state_ = 1; return 1;
case 1:
if (idx_ < n_) {
idx_++;
return 2;
}
else {
state_ = 2;
}
break;
case 2:
completed_ = true;
return 3;
}
}
boolean isCompleted() { return completed_; }
}
public static void main (String[] args) throws java.lang.Exception
{
Generator g = new Generator(5);
while (! g.isCompleted()) {
int x = g.generate();
System.out.println(x + "");
}
}
}
Both are moving for the time being.
Do you already have a code generator like this?
In an era when the yield statement can be used normally in a browser, you don't have to think about this.
Recommended Posts