如何递归地实现lambas。
how to implement lambas recursively.
推荐答案解决方案1非常好但是它留下了一个漏洞的错误。 这取决于递归调用绑定到名称 factorialValue 。 如果被泄露它就会崩溃。 非常人为的例子: Solution 1 is pretty good but it leaves a vulnerability for error. It depends on the binding to the name factorialValue for the recursive call. If were compromised it falls apart. Very contrived example: Func<int, int> Factorial = null; Factorial = x => (x <= 0) ? 1 : x * Factorial(x - 1); Func<int, int> incorrectFactorial = Factorial; Factorial = x => x; int ans = incorrectFactorial(5);
由于重新分配了标识符<$ c $,因此 ans 的值为20 c> Factorial 。 绑定递归方法的名称需要保护:
The value of ans here is 20 because of the reassignment of the identifier Factorial. The name binding the recursive method needs to be protected:
Func<int, int> Factorial = null; Factorial = x => { Func<int, int> internalFactorial = null; internalFactorial = xi => (xi <= 0) ? 1 : xi * internalFactorial(xi - 1); return internalFactorial(x); }; Func<int, int> otherFactorial = Factorial; Factorial = x => x; int ans = otherFactorial(5);这里 ans 的值是正确的120,因为递归标识符是范围内部的of lambda。 另一种方法是使用一个方法返回 Func< int,int> :
Here the value of ans is the correct 120 because the recursion identifier was internal to the scope of the lambda. Another way to accomplish this would be to have a method that returns a Func<int, int>:
static Func<int, int> GetFactorialFunction() { Func<int, int> Factorial = null; Factorial = x => (x <= 0) ? 1 : x * Factorial(x - 1); return Factorial; }并调用返回的函数:
and invoke the returned function:
int ans = GetFactorialFunction()(5);Of当然,此时使用lambda 可能是多余的,因为函数可以直接实现为命名的递归函数。
Of course, at this point using a lambda is probably superfluous since the function could be implemented directly as a named, recursive function.
可以递归地实现lambda。 试试这个例子 Its possible to implement lambda recursively. Try this as an example Func<int, int> factorialValue = null; factorialValue = x => (x == 0) ? 1 : x * factorialValue(x - 1);
更多推荐
递归地实现lambdas
发布评论