Reputation: 10124
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.
}
};
Upvotes: 32
Views: 6516
Reputation: 887767
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.
Upvotes: 59