各种语言的Python生成器
如何在您最喜欢的语言中模拟Python样式生成器?我在Scheme中找到了此。看到其他实现必须很有趣,尤其是那些没有第一类继承的语言。
How do you emulate Python style generators in your favorite language? I found this one in Scheme. It must be interesting to see other implementations, especially in those languages that don't have first-class continuations.
下面是C ++中使用光纤模拟生成器的示例:
Here is an example in C++ that simulates generators using fibers:
yield return迭代器是为
创建的
语言特性,一个原因:简单。它是
通常更容易迭代
跨整个collectionl,存储所有
上下文需要在局部变量
而不是制作一个复杂的
自定义迭代器对象存储
The "yield return" iterator is a language feature that was created for one reason: simplicity. It is generally much easier to iterate across whole collectionl, storing all context needed in local variables, rather than crafting a complicated, custom iterator object that stores its state across subsequent retrieval operations.
还有原语 C例程 setjmp,longjmp 来获得类似的结果。
(Lua 协议使用上述方法实现)
There are also the primitive C routines setjmp, longjmp to achieve similar results.
(Lua coroutines are implemented with the above method)