-
-
Save lontivero/65a84df061bfe9e9f30beffa80fcfc18 to your computer and use it in GitHub Desktop.
Monoid and Foldable for C#
This file contains hidden or 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
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