Generator (computer programming): Difference between revisions

Content deleted Content added
Jespdj (talk | contribs)
m Java: Small fix in fibo Java example.
Line 374:
System.out.println("next Fibonacci number is " + f);
if (someCondition(f)) break;
}
</source>
 
 
Also the Fibonacci sequence could also be written using java 8 Stream interface:
<source lang="java">
Stream.generate(new Supplier<Integer>() {
int a = 1;
int b = 2;
 
public Integer get() {
int temp = a;
a = b;
b = a + temp;
return temp;
}
}).forEach(System.out::print);
</source>
 
Or may be written using Iterable interface:
<source lang="java">
public Iterable<Integer> fibonacci(int limit){
return ()->{
return Stream.generate(new Supplier<Integer>() {
int a = 1;
int b = 2;
public Integer get() {
int temp = a;
a = b;
b = a + temp;
return temp;
}
}).limit(limit).iterator();
}
}
 
// this could then be used as...
for (int f: fibonacci(10)) {
System.out.println("next Fibonacci number is " + f);
}
</source>