开发者

How to call this func code snippet?

I am looking at this article on monads:

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

I am writing the code in my copy of VS2010, but for the following code:

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

How do I call this?

Also, the article states:

Function composition takes two functions and plumbs the result from the second function into the input of the first function, thereby forming one function.

开发者_JAVA百科Is this not just pipelines?

The code sample:

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

Does not compile.

Also, what

Thanks


This doesn't work? Note that the Extension method has to be in a public static class and the method itself must be static.

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;
    }
}

Also notice that f1: double -> double and g1: double -> double.

In the compose function

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

so f.g: V -> T

In other words in my example, not all types had to be double. You just have to make sure that the domain of the function f (the outer function) includes the range of the function g (the inner function). In programming this means that the return type of g needs to be the same as (or implicitly cast to) the parameter type of f.


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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜