c# - C# 是否支持函数组合?

标签 c# .net haskell composition

在最新版本的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/

相关文章:

c# - 具有通用服务和存储库代码的 .NET Core 依赖注入(inject)错误

c# - 帮助设计经理类

Haskell初学者订单函数

c# - 事件 : Null exception 中的 OperationContext.Current

C# - 编写 COM 服务器 - 映射到方法的属性

c# - 如何更改 WinForms 中的 View ?

.net - 寻找 .NET 库来进行支持多个源的身份验证

haskell - Comonads 或 Representable 上的镜头

haskell - [Char] a -> IO a 函数

c# - MVC Ajax.ActionLink 找不到 POST 方法