在C#中是否需要定点组合器? [英] Do we need fixed point combinators in C#?

查看:45
本文介绍了在C#中是否需要定点组合器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中使用递归lambda,并在网上找到了两种方法来做到这一点.一种方法使用不动点组合器,而另一种方法则没有.在下面的代码中,f1是使用combinator构建的,而f2是直接定义的.我的问题是,我们需要C#的定点组合器还是该语言已经提供了我们所需的一切,所以我们可以不理会它们吗?

I was playing with recursive lambdas in C# and have found two approaches to do this on the web. One approach uses fixed point combinator and the other does not. In the code below f1 is built using combinator, and f2 is defined directly. My question is, do we need fixed point combinators in C# or the language already provides all we need, so we can leave them alone?

class Program
{
    static Func<T, T> F<T>(Func<Func<T,T>,Func<T,T>> f)
    {
        return x => f(F(f))(x);
    }

    static void Main(string[] args)
    {
        Func<Func<int,int>,Func<int,int>> f = fac => x => x == 0 ? 1 : x * fac(x - 1);
        var f1 = F(f);

        Console.WriteLine(f1(5));

        Func<int, int> f2 = null;
        f2 = x => x == 0 ? 1 : x * f2(x - 1);

        Console.WriteLine(f2(5));
    }
}

推荐答案

我们可以为方法命名,这意味着该语言已经内置了对递归的必要支持.

As we can give a name to a method, that means that the language already has the necessary support for recursion built into it.

请注意,问题中给出的第二种方法涉及在引入变量后更改变量的值,从而使其不是纯"函数式编程.仅当您的函数演算系统没有内置的可在定义完全定义之前通过名称引用其定义的函数的内置概念时,才需要使用Y组合器.C#有两种直接执行此操作的方法:1.最初将函数变量定义为null和2.声明一个普通的命名方法(到目前为止是首选技术).

Note that the second method given in your question involves changing the value of a variable after it has been introduced, making it not "pure" functional programming. Y-combinator is only necessary if your system of functional calculus doesn't have a built-in notion of a function that can refer to its own definition by name before the definition is completely defined. C# has two ways to do that directly: 1. initially defining the function variable as null and 2. declaring an ordinary named method (by far the preferred technique).

这篇关于在C#中是否需要定点组合器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆