generate with state
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 2 16:08:53 PST 2015
On 11/02/2015 03:56 PM, Freddy wrote:
> Is there a version of http://dlang.org/phobos/std_range.html#.generate
> with state.
generate() already allows "callables", which can be a delegate:
import std.stdio;
import std.range;
struct S {
int i;
int fun() {
return i++;
}
}
void main() {
auto s = S(42);
writefln("%(%s %)", generate(&s.fun).take(5));
}
Prints
42 43 44 45 46
Shorter but more cryptic:
... generate(&S(42).fun).take(5)
If the generation process is naturally recursive like traversing a tree,
then you may want to consider std.concurrency.Generator (which does not
involve multiple threads at all):
http://dlang.org/phobos/std_concurrency.html#.Generator
Here is an example:
http://ddili.org/ders/d.en/fibers.html#ix_fibers.Generator,%20std.concurrency
import std.stdio;
import std.range;
import std.concurrency;
/* This alias is used for resolving the name conflict with
* std.range.Generator. */
alias FiberRange = std.concurrency.Generator;
void fibonacciSeries() {
int current = 0;
int next = 1;
while (true) {
yield(current);
const nextNext = current + next;
current = next;
next = nextNext;
}
}
void main() {
auto series = new FiberRange!int(&fibonacciSeries);
writefln("%(%s %)", series.take(10));
}
Ali
More information about the Digitalmars-d-learn
mailing list