在最新版本的C#中,我可以做类似Haskell的函数组合吗? more... ?
Function composition is the act of pipelining the result of one function, to the input of another, creating an entirely new function.
我觉得 linq 是最接近的,但那是链接,而不是函数组合,对吧?
最佳答案
public static class Extensions
{
public static Func<T, TReturn2> Compose<T, TReturn1, TReturn2>(this Func<TReturn1, TReturn2> func1, Func<T, TReturn1> func2)
{
return x => func1(func2(x));
}
}
用法:
Func<int, int> makeDouble = x => x * 2;
Func<int, int> makeTriple = x => x * 3;
Func<int, string> toString = x => x.ToString();
Func<int, string> makeTimesSixString = toString.Compose(makeDouble).Compose(makeTriple);
//Prints "true"
Console.WriteLine(makeTimesSixString (3) == toString(makeDouble(makeTriple(3))));
关于c# - C# 是否支持函数组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5264060/