a yield return operation can be regarded as
- put some checkpoint there
- write a value in somewhere
- when resume is acquired, jump to instruction next to it.
therefore I implement it as a state machine alike class, coroutine.
within this mechanism, each instruction has its instruction pointer, index, and
instruction may has a label along with it, so we can use jmp(label) to jump to the label.
- add some mechanism to achieve a goto syntax: addInstruction(..) and jmp()
- and store status/variable in somewhere: setVariable(name,value), yield(value)
- a way to temporarily suspend / resume: exec()
for example:
public class FibbonaciCoroutine implements Iterator<BigInteger> {
BigInteger[] bucket = { new BigInteger("1"), new BigInteger("1"), new BigInteger("0") };
int idx = 2;
Coroutine coroutine = new Coroutine((pthis) -> {
pthis.addInstruction("_label1", (me) -> {
int p1 = idx - 2;
int p2 = idx - 1;
if (p1 < 0)
p1 += 3;
if (p2 < 0)
p2 += 3;
bucket[idx] = bucket[p1].add(bucket[p2]);
idx = (idx + 1) % bucket.length;
me.yield(bucket[idx]);
});
// goto
pthis.addInstruction((me) -> {
me.jmp("_label1");
});
pthis.start();
});
@Override
public boolean hasNext() {
return !coroutine.isStopped();
}
@Override
public BigInteger next() {
while (coroutine.exec())
;
return coroutine.getYieldValue();
}
public static void main(String[] argv) {
FibbonaciCoroutine cor = new FibbonaciCoroutine();
for (int i = 0; i < 100 && cor.hasNext(); ++i) {
System.out.printf("%d ", cor.next());
}
}
}
see FibonacciCoroutine.java
Back to your question...
LinkedListObject<something> current = first;
While (current != null){
yield return current.getValue();
current = current.getNext()
}
is able to convert to following code
//some where in class, or use Var<> to wrap it.
Var<LinkedListObject<something> > current = new Var<>(first);
Coroutine cor = new Coroutine();
cor.While((ins)->current.get() != null).run((ins)->{
ins.addInstruction((c)->c.yield(current.get().getValue()) );
// wrap it with lambda for being a checkpoint
ins.addInstruction( (c)->current.set(current.get().getNext()) );
});
so we can use its getYieldValue() to retrive result, or simply call
coroutine.iterator to convert coroutine into an iterator