Created
November 8, 2018 02:27
-
-
Save sampathsris/e862e64540aa2778c788cba8ce6fd975 to your computer and use it in GitHub Desktop.
A function composer in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
namespace IntObjectTest | |
{ | |
public class Composer | |
{ | |
static void Main() | |
{ | |
Func<string, Func<string, string>> createAdder = s => x => x + s; | |
var a = createAdder("a"); | |
var b = createAdder("b"); | |
var c = createAdder("c"); | |
var f = Compose(a, b, c); | |
Console.WriteLine(a("_")); // outputs: _a | |
Console.WriteLine(b("_")); // outputs: _b | |
Console.WriteLine(c("_")); // outputs: _c | |
Console.WriteLine(f("_")); // outputs: _cba | |
} | |
public static Func<T, T> Compose<T>(params Func<T, T>[] chain) | |
{ | |
// If the list of functions is: | |
// a, b, c, ..., z | |
// then we want to compose the functions such that the returned | |
// function is: | |
// (arg) => a(b(c(...(z(arg))...))) | |
return (T arg) => chain | |
.Reverse<Func<T, T>>() | |
.Aggregate<Func<T, T>, T>( | |
arg, | |
(acc, func) => func(acc) | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a C# equivalent for the
compose
in Redux.