IEnumerable<int> nats =
for (i in range(0,42))
yield i*2
String phrase = "I want to buy some cheese.";
IEnumerable<int> substrs =
for (i in 0 .. phrase.length)
for (j in i .. phrase.length+1)
yield phrase[i..j]
这里我假设正确的端点不包含在范围内。
说实话,当我在 Python 中看到这个时,我不得不想:“代价是什么?”
There's also Python's approach--no special syntax for generators; the presence of a "yield" statement is all it takes. Any statements that takes a block could be used, though I'd expect to find only loops used in practice:
IEnumerable<int> nats =
for (i in range(0,42))
yield i*2
String phrase = "I want to buy some cheese.";
IEnumerable<int> substrs =
for (i in 0 .. phrase.length)
for (j in i .. phrase.length+1)
yield phrase[i..j]
Here I'm assuming the right endpoint isn't included in a range.
To be completely honest, when I saw this in Python, I had to wonder: "at what cost?"
发布评论
评论(3)
还有 Python 的 方法——生成器没有特殊的语法;只要有一个“产量”声明就可以了。任何采用块的语句都可以使用,尽管我希望只找到实践中使用的循环:
这里我假设正确的端点不包含在范围内。
说实话,当我在 Python 中看到这个时,我不得不想:“代价是什么?”
There's also Python's approach--no special syntax for generators; the presence of a "yield" statement is all it takes. Any statements that takes a block could be used, though I'd expect to find only loops used in practice:
Here I'm assuming the right endpoint isn't included in a range.
To be completely honest, when I saw this in Python, I had to wonder: "at what cost?"
看看 F# 做了什么。您可以执行
以下操作,其中 seq-expr 是一种包含大多数语言结构以及“yield”的形式。例如,您可以编写
F# 编译器将此代码转换为 IEnumerable 的状态机实现(就像 C# 对迭代器块所做的那样)。
我喜欢这种语法,因为它意味着您可以编写与“现在执行命令式操作”完全相同的代码,例如,
但将该代码包装在 seq{} 中并使用“yield”,并且该代码将变为惰性 IEnumerable。
Check out what F# does. You can do
where seq-expr is a form that includes most language constructs along with 'yield'. So e.g. you can write
The F# compiler translates this code into a state machine implementation of IEnumerable (like C# does for iterator blocks).
I like this syntax because it means e.g. you can write the exact same code you would write to "do imperative stuff now", e.g.
but wrap that code in seq{} and use 'yield' and the code becomes a lazy IEnumerable instead.