C#:使用 Lambda 的递归函数

发布于 2024-07-26 06:02:50 字数 608 浏览 4 评论 0原文

以下内容无法编译:

Func<int, int> fac = n => (n <= 1) ? 1 : n * fac(n - 1);

局部变量“fac”可能不是 访问前初始化

如何使用 lambda 来创建递归函数?

[更新]

这里还有两个我觉得有趣的链接:

  1. Eric Lippert 的“为什么递归 lambda 会导致明确的赋值错误?”
  2. C# 中的匿名递归

The below does not compile:

Func<int, int> fac = n => (n <= 1) ? 1 : n * fac(n - 1);

Local variable 'fac' might not be
initialized before accessing

How can you make a recursive function with lambdas?

[Update]

Here are also two links that I found interesting to read:

  1. Eric Lippert's "Why does a recursive lambda cause a definite assignment error?"
  2. Anonymous Recursion in C#

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

往事风中埋 2024-08-02 06:02:50

C# 不支持这种特殊风格的函数作为单行声明。 您必须将声明和定义分成两行

Func<int, int> fac = null;
fac = n => (n <= 1) ? 1 : n * fac(n - 1);

This particular style of function is not supported by C# as a single line declaration. You have to separate out the declaration and definition into 2 lines

Func<int, int> fac = null;
fac = n => (n <= 1) ? 1 : n * fac(n - 1);
無心 2024-08-02 06:02:50

您必须先创建 fac 并稍后分配它(这非常无用,因为它依赖于多重分配)或使用所谓的 Y 组合器

示例:

delegate Func<TIn, TOut> FixedPointFunction<TIn, TOut>(Func<TIn, TOut> f);

static Func<T, TRes> Fix<T, TRes>(FixedPointFunction<T, TRes> f) {
    return f(x => Fix(f)(x));
}

static void Main(string[] args) {

    var fact = Fix<int, int>(f => x => (x <= 1) ? x : x * f(x - 1));

    Console.WriteLine(fact(5));            
}

但请注意,这可能有点难以阅读/理解。

You'll have to create fac first und assign it later (which is pretty unfunctional because it depends on multiple assignment) or use so called Y-combinators.

Example:

delegate Func<TIn, TOut> FixedPointFunction<TIn, TOut>(Func<TIn, TOut> f);

static Func<T, TRes> Fix<T, TRes>(FixedPointFunction<T, TRes> f) {
    return f(x => Fix(f)(x));
}

static void Main(string[] args) {

    var fact = Fix<int, int>(f => x => (x <= 1) ? x : x * f(x - 1));

    Console.WriteLine(fact(5));            
}

But note that this might be somewhat hard to read/understand.

拥醉 2024-08-02 06:02:50

从 C# 7.0 开始,您终于可以通过使用 本地函数 而不是 lambda。

int fac(int n) => (n <= 1) ? 1 : n * fac(n - 1);

Since C# 7.0 you finally can do a similar thing by using a local function instead of a lambda.

int fac(int n) => (n <= 1) ? 1 : n * fac(n - 1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文