递归地实现lambdas

编程入门 行业动态 更新时间:2024-10-23 19:23:32
本文介绍了递归地实现lambdas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何递归地实现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

本文发布于:2023-11-30 20:32:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651395.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   lambdas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!