Skip to content

Instantly share code, notes, and snippets.

@lontivero
Forked from reidev275/Monoid.cs
Last active July 15, 2020 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lontivero/65a84df061bfe9e9f30beffa80fcfc18 to your computer and use it in GitHub Desktop.
Save lontivero/65a84df061bfe9e9f30beffa80fcfc18 to your computer and use it in GitHub Desktop.
Monoid and Foldable for C#
public interface Monoid<A>
{
public A Empty => default(A);
A Append(A x, A y);
}
public static class Foldable
{
public static A Fold<A>(this IEnumerable<A> list, Monoid<A> M) =>
list.FoldMap(x => x, M);
public static A FoldMap<A, B>(this IEnumerable<B> list, Func<B, A> f, Monoid<A> M) =>
list.Aggregate(M.Empty, (p, c) => M.Append(p, f(c)));
}
public class SumDecimal : Monoid<decimal>
{
public decimal Append(decimal x, decimal y) => Decimal.Add(x, y);
}
var people = new List<Person>
{
new Person { Name = "Reid", Age = 36 },
new Person { Name = "Miles", Age = 6 }
};
var totalAge = people.FoldMap(x => x.Age, new SumDecimal());
//totalAge = 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment