Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active July 15, 2020 14:52
Show Gist options
  • Save reidev275/4058a570744b4f74713b9ee81dd4cc3a to your computer and use it in GitHub Desktop.
Save reidev275/4058a570744b4f74713b9ee81dd4cc3a to your computer and use it in GitHub Desktop.
Monoid and Foldable for C#
public interface Monoid<A>
{
A Empty { get; }
A Append(A x, A y);
}
public static class Foldable
{
public static A Fold<A>(this IEnumerable<A> list, Monoid<A> M)
{
return list.FoldMap(x => x, M);
}
public static A FoldMap<A, B>(this IEnumerable<B> list, Func<B, A> f, Monoid<A> M)
{
return list.Aggregate(M.Empty, (p, c) => M.Append(p, f(c)));
}
}
public class SumDecimal : Monoid<decimal>
{
public decimal Empty => 0;
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