Is it possible to do recursion with an Func delegate? I have the following, which doesn't compile because the name of the Func isn't in scope...
Func<long, long, List<long>, IEnumerable<long>> GeneratePrimesRecursively = (number, upperBound, primeFactors) => { if (upperBound < number) { return primeFactors; } else { if (!primeFactors.Any(factor => number % factor == 0)) primeFactors.Add(number); return GeneratePrimesRecursively(++number, upperBound, primeFactors); // breaks here. } };
Techopedia Explains Recursive Function Simple examples of a recursive function include the factorial, where an integer is multiplied by itself while being incrementally lowered. Many other self-referencing functions in a loop could be called recursive functions, for example, where n = n + 1 given an operating range.
Recursive Function is a function that repeats or uses its own previous term to calculate subsequent terms and thus forms a sequence of terms. Usually, we learn about this function based on the arithmetic-geometric sequence, which has terms with a common difference between them.
The C programming language allows any of its functions to call itself multiple times in a program. Here, any function that happens to call itself again and again (directly or indirectly), unless the program satisfies some specific condition/subtask is called a recursive function.
Like this:
Func<...> method = null; method = (...) => { return method(); };
Your code produces an error because you're trying to use the variable before you assign it.
Your lambda expression is compiled before the variable is set (the variable can only be set to a complete expression), so it cannot use the variable.
Setting the variable to null
first avoids this issue, because it will already be set when the lambda expression is compiled.
As a more powerful approach, you can use a YCombinator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With