문제

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.

도움이 되었습니까?

해결책

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;
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top