Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion with Func

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.     } }; 
like image 378
t3rse Avatar asked Jan 06 '11 03:01

t3rse


People also ask

What is function recursion with example?

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.

What is meant by recursive function?

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.

What is recursion function in C?

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.


1 Answers

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.

like image 169
SLaks Avatar answered Sep 20 '22 21:09

SLaks