Does C# support function composition?

Joan Venge picture Joan Venge · Mar 10, 2011 · Viewed 9.8k times · Source

In the latest version of C#, can I do something like this?

I feel like linq is the closest but that's chaining, not function composition, right?

Answer

Davy8 picture Davy8 · Mar 10, 2011
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));
    }
}

Usage:

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