Skip to content

Instantly share code, notes, and snippets.

@sblom
Last active January 25, 2021 19:31
Show Gist options
  • Save sblom/4378713 to your computer and use it in GitHub Desktop.
Save sblom/4378713 to your computer and use it in GitHub Desktop.
Toy implementation of Clojure 1.5's reducers library in C# (using LINQPad). https://www.clojure.org/news/2012/05/15/anatomy-of-reducer
List<int> ns = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
Func<Func<int,int>,Func<Func<int,int,int>,Func<int,int,int>>> mapping = delegate(Func<int,int> f) {
return (Func<int,int,int> f1) => ((int r, int i) => f1(r,f(i)));
};
Func<Func<int,bool>,Func<Func<int,int,int>,Func<int,int,int>>> filtering = delegate(Func<int,bool> pred) {
return (Func<int,int,int> f1) => ((int r, int i) => {
if (pred(i))
return f1(r,i);
else
return r;
});
};
Func<int,int> half = n => n / 2;
Func<int,int> inc = n => n + 1;
Func<int,int,int> plus = (a, b) => a + b;
Func<int,bool> isEven = n => n % 2 == 0;
ns.Where(isEven).Select(half).Aggregate(0,plus).Dump("LINQ");
ns.Aggregate(0,filtering(isEven)(mapping(half)(plus))).Dump("Clojure Reducer");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment