0

私はモナドに関するこの記事を見ています:

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

これをどのように呼びますか?

また、記事には次のように記載されています。

関数合成は2つの関数を取り、2番目の関数の結果を最初の関数の入力に組み込むことで1つの関数を形成します。

これはパイプラインだけではありませんか?

コードサンプル:

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

コンパイルしません。

また、何

ありがとう

4

2 に答える 2

5

これは機能しませんか?Extensionメソッドはパブリック静的クラスに含まれている必要があり、メソッド自体は静的である必要があることに注意してください。

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

言い換えれば、私の例では、すべてのタイプがdoubleである必要はありませんでした。関数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 に答える