0

我正在看这篇关于 monads 的文章:

http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx

我在我的 VS2010 副本中编写代码,但是对于以下代码:

public static Func<T, V> Compose<T, U, V>(this Func<U, V> f, Func<T, U> g)
{
    return x => f(g(x));
}

我怎么称呼这个?

此外,文章指出:

函数组合采用两个函数,并将第二个函数的结果输入到第一个函数的输入中,从而形成一个函数。

这不仅仅是管道吗?

代码示例:

var r = f.Compose(g)(x);

不编译。

还有,什么

谢谢

4

2 回答 2

5

这不行吗?请注意,扩展方法必须在公共静态类中,并且方法本身必须是静态的。

public static class FunctionalExtensions
{
    public static Func<T, V> Compose<T, U, V>(this Func<U, V> f, Func<T, U> g)
    {
        return x => f(g(x));
    }
}

class Program
{
    static void Main(string[] args)
    {
        Func<double, double> 
            f1 = Square,         // Func<double, double> is a delegate type so we have to create
            g1 = AddOne,         // an instance for both f and g
            h1 = f1.Compose(g1); // This is a Func<double, double> now, (i.e. h(X) = f(g(x)) )

        // To call new function do this
        double result1 = h1(5.0);

        Func<double, double>
            f2 = x => x*x,       
            g2 = x => x + 1,       
            h2 = f2.Compose(g2);

        // To call new function do this
        double result2 = h2(5.0);
    }

    public static double Square(double x)
    {
        return x * x;
    }

    public static double AddOne(double x)
    {
        return x + 1;
    }
}

还要注意 f1: double -> double 和 g1: double -> double。

在撰写功能中

f: V -> U 和 g: U -> T

所以 fg: V -> T

换句话说,在我的示例中,并非所有类型都必须是双精度的。您只需确保函数 f(外部函数)的域包括函数 g(内部函数)的范围。在编程中,这意味着 g 的返回类型需要与 f 的参数类型相同(或隐式转换为)。

于 2011-09-09T13:18:42.240 回答
0
public static class Extensions
{
    // Note extension methods need to be defined in a static class
    public static Func<T, V> Compose<T, U, V>(this Func<U, V> f, Func<T, U> g)
    {
        return x => f(g(x));
    }
}

public class CallingClass
{
    public void CallingMethod()
    {
        Func<string, int> f1 = s => int.Parse(s);
        Func<int, double> f2 = i => i / 2.0;

        // Note which way round f1 and f2 go
        Func<string, double> composed = f2.Compose(f1);

        var result = composed("3");

        // Now result == 1.5
    }
}
于 2011-09-09T13:20:51.053 回答