Skip to content

Instantly share code, notes, and snippets.

@sampathsris
Created November 8, 2018 02:27
Show Gist options
  • Save sampathsris/e862e64540aa2778c788cba8ce6fd975 to your computer and use it in GitHub Desktop.
Save sampathsris/e862e64540aa2778c788cba8ce6fd975 to your computer and use it in GitHub Desktop.
A function composer in C#
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)
);
}
}
}
@sampathsris
Copy link
Author

This is a C# equivalent for the compose in Redux.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment