Yield from function?
Profile Anaysis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jan 31 03:00:19 PST 2017
On Tuesday, 31 January 2017 at 06:32:02 UTC, Ali Çehreli wrote:
> On 01/30/2017 08:12 PM, Profile Anaysis wrote:
>>
>> import std.stdio, std.concurrency, core.thread;
>>
>> class Search : Fiber
>> {
>> this() { super(&start); }
>> int res = 0;
>> void start()
>> {
>> Fiber.yield();
>> res = 1;
>> }
>> }
>>
>> void main()
>> {
>>
>> auto search = new Search();
>>
>> search.call(); writeln(search.res);
>> search.call(); writeln(search.res);
>> search.call(); writeln(search.res); // crashes after 3rd
>> call(first
>> two work fine)
>> }
>
> That's because the fiber is not in a callable state. (You can
> check with search.state.) Here is one where the fiber function
> lives (too) long:
>
> import std.stdio, std.concurrency, core.thread;
>
> class Search : Fiber
> {
> this() { super(&start); }
> int res = 0;
> void start() {
> while (true) {
> Fiber.yield();
> ++res;
> }
> }
> }
>
> void main()
> {
> auto search = new Search();
>
> foreach (i; 0 .. 5) {
> search.call();
> writeln(search.res);
> }
> }
>
> Ali
Just curious, how can I use start() recursively?
I would like to iterate over a recursive structure and yield for
each "solution". I could use a stack to store the values but the
whole point of the fiber was to avoid that.
void start() {
while (true) {
Fiber.yield();
++res;
}
}
Seems I can't create start with a parameter and non-void return
type. This seems to make it about useless to use a fiber
recursively because no pushing and popping on the stack occur.
class Search : Fiber
{
this() { super(&start); }
bool End = false;
int res = 0;
void start() {
while (!End)
{
int Foo(int x)
{
Fiber.yield();
if (x < 10)
{
res = Foo(x++);
return res;
}
else
return x;
}
}
}
void main()
{
auto search = new Search();
foreach (i; 0 .. 5)
{
search.call();
writeln(search.res);
}
search.End = true;
}
My goal is simple, to yield a solution at each step in the
recursive process.
Maybe I can use another fiber using the lambda syntax?
More information about the Digitalmars-d-learn
mailing list