Question

I'm trying to do something that combines using yield and recursion and I don't really understand why it's not working.

Since my code is complicated, I've generated a simple example with the Fibonacci series:

        private IEnumerable<int> fib()
        {
            int a1 = 1, a2 = 1;
            return fibRec(a1, a2);
        }

        private IEnumerable<int> fibRec(int a, int b)
        {
            int tmp = a;
            a = b;
            b = tmp + b;
            yield return a;
            fibRec(a, b);
        }

Now, I know there are a 1000 ways of solving Fibonacci, but it's not the deal here. this is only an example.

Here is my call:

var nums = fib().Take(50).ToList();

The recursive call doesn't "work".
I get the first yield to work OK and I don't really under stand why this suddenly stops when I try to call myself again.
Doing this with "while(true)" and no recursive call will work just fine.

Was it helpful?

Solution

You need to iterate though the enumerable returned by the recursive call and yield return each of the items explicitly.

    private IEnumerable<int> fibRec(int a, int b)
    {
        int tmp = a;
        a = b;
        b = tmp + b;
        yield return a;
        foreach(int val in fibRec(a, b))
        {
             yield return val;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top