這是一個非常簡單的想法。你想要的是:
until both lists A and B exhausted
while not (A exhausted or processing A has failed)
process next element of A
while not (B exhausted or processing B has failed)
process next element of B
現在你可以翻譯最正常的任何迭代語言。在C中,
for (int ia = 0, ib = 0; ia < a_len || ib < b_len;) {
while (ia < a_len) if (process(a[ia++]) == FAIL) break;
while (ib < b_len) if (process(b[ib++]) == FAIL) break;
}
但是不同的語言提供了其他表達方式。一個很好的例子是co-routines。
coroutine processA
while A not empty and process(nextElement(A)) != FAIL, /* empty */ ;
if not empty(B) yield B
coroutine processB
while B not empty and process(nextElement(B)) != FAIL, /* empty */ ;
if not empty(A) yield A
精美的對稱,不是嗎?
使用兩個類似於合併操作完成的迭代器變量 – user3080953