我在monad上看这篇文章:
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));
}
Run Code Online (Sandbox Code Playgroud)
我怎么称呼这个?
此外,文章指出:
函数组合采用两个函数,并将第二个函数的结果输入到第一个函数的输入中,从而形成一个函数.
这不仅仅是管道吗?
代码示例:
var r = f.Compose(g)(x);
Run Code Online (Sandbox Code Playgroud)
不编译.
什么
谢谢
这不起作用?请注意,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;
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意f1:double - > double和g1:double - > double.
在撰写功能
f:V - > U和g:U - > T.
所以fg:V - > T.
换句话说,在我的例子中,并非所有类型都必须加倍.您只需要确保函数f的域(外部函数)包含函数g的范围(内部函数).在编程中,这意味着g的返回类型需要与f的参数类型相同(或隐式地转换为).
| 归档时间: |
|
| 查看次数: |
289 次 |
| 最近记录: |