Content deleted Content added
→F#: 1.9.1 |
No edit summary |
||
Line 23:
In the presence of generators, loop constructs of a language – such as for and while – can be reduced into a single loop ... end loop construct; all the usual loop constructs can then be comfortably simulated by using suitable generators in the right way. For example, a ranged loop like <code>for x = 1 to 10</code> can be implemented as iteration through a generator, as in Python's <code>for x in range(10, 1)</code>. Further, <code>break</code> can be implemented as sending ''finish'' to the generator and then using <code>continue</code> in the loop.
==
Generators first appeared in [[CLU programming language|CLU]] (1975),<ref>{{cite web
Line 164:
use strict;
use warnings;
#
use Coro::Generator;
#
my $chars = ['A'...'Z'];
#
my $letters = generator {
};
#
print $letters->(), "\n" for (0..15);
Line 282 ⟶ 281:
foreach (fibonacci() as $number) {
echo $number
}
</source>
Line 290 ⟶ 289:
<source lang="ruby">
# Generator from an Enumerator object
chars = Enumerator.new(['A', 'B', 'C', 'Z'])
Line 303 ⟶ 301:
100.times { puts count.next }
</source>
Line 316 ⟶ 313:
<source lang="Java">
// Iterator implemented as anonymous class. This uses generics but doesn't need to.
for (int i: new Iterator<Integer>() {
int counter = 1;
@Override
public boolean hasNext() {
return counter <= 100;
}
Line 340 ⟶ 337:
An infinite Fibonacci sequence could also be written as an Iterator:
<source lang="java">
Iterator<Integer> fibo = new Iterator<Integer>() {
int a = 1;
int b = 1;
int total;
Line 364 ⟶ 361:
}
// this could then be used as...
for(int f: fibo) {
System.out.println("next Fibonacci number is " + f);
if (someCondition(f)) break;
}
</source>
Line 389 ⟶ 386:
<source lang="csharp">
public class CityCollection : IEnumerable<string> {
public IEnumerator<string> GetEnumerator() {
yield return "New York";
yield return "Paris";
yield return "London";
}
}
</source>
Line 412 ⟶ 409:
// An implicit declaration of I as an integer is therefore made here
for I in 1..5 loop
IO.WriteLn "I=", I
</source>
Line 421 ⟶ 418:
seq { for b in 0 .. 25 do
if b < 15 then
yield b * b }
</source>
forms a sequence of squares of numbers from 0 to 14 by filtering out numbers from the range of numbers from 0 to 25.
Line 452 ⟶ 449:
p = []
while True:
# This works in Python 2.5+
if not any(
itertools.takewhile(lambda f: f*f <= n, p)
yield n
p.append(
n += 2
</source>
Line 464 ⟶ 461:
PEP 380 (implemented in Python 3.3) adds the <tt>yield from</tt> expression, allowing a generator to delegate part of its operations to another generator.<ref name="pep380">[https://www.python.org/dev/peps/pep-0380/ PEP 380 -- Syntax for Delegating to a Subgenerator]</ref>
====Generator
Python has a syntax modeled on that of [[list comprehension]]s, called a generator expression that aids in the creation of generators.
|