Does C# support function composition?
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))));
I did not let the compiler check this, but this should be possible:
public static Func<T3,T1> my_chain<T1, T2, T3>(Func<T2,T1> f1, Func<T3,T2> f2)
{
return x => f2(f1(x));
}
There is no specific operator / "syntax sugar" for that in C# (however, in F# you would use the >>
operator).
There is a great blog post on this subject from Matthew Podwysocki. He suggests this kind of construct in C#:
public static class FuncExtensions
{
public static Func<TSource, TResult> ForwardCompose<TSource, TIntermediate, TResult>(
this Func<TSource, TIntermediate> func1, Func<TIntermediate, TResult> func2)
{
return source => func2(func1(source));
}
}
Func<Func<int, int>, IEnumerable<int>, IEnumerable<int>> map = (f, i) => i.Select(f);
Func<Func<int, bool>, IEnumerable<int>, IEnumerable<int>> filter = (f, i) => i.Where(f);
Func<int, Func<int, int, int>, IEnumerable<int>, int> fold = (s, f, i) => i.Aggregate(s, f);
// Compose together
var mapFilterFold = map.Apply(x => x * x * x)
.ForwardCompose(filter.Apply(x => x % 3 == 0))
.ForwardCompose(fold.Apply(1, (acc, x) => acc * x));
Console.WriteLine(mapFilterFold(Enumerable.Range(1, 10)));