使用 Func 进行递归
是否可以使用 Func 委托进行递归?我有以下内容,但无法编译,因为 Func 的名称不在范围内......
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.
}
};
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.
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样:
您的代码会产生错误,因为您在分配变量之前尝试使用该变量。
您的 lambda 表达式是在设置变量之前编译的(变量只能设置为完整表达式),因此它无法使用该变量。
首先将变量设置为
null
可以避免此问题,因为在编译 lambda 表达式时已经设置了该变量。作为更强大的方法,您可以使用 YCombinator。
Like this:
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.