-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
45 lines (38 loc) · 898 Bytes
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var intMonoids = new List<IntegerMonoid>
{
new IntegerMonoid(0),
new IntegerMonoid(1),
new IntegerMonoid(1),
new IntegerMonoid(2),
new IntegerMonoid(3),
new IntegerMonoid(5)
};
Console.WriteLine($"Fold: {FoldableMonoid.Fold(intMonoids)?.Value}");
}
}
public class IntegerMonoid : Monoid<IntegerMonoid>
{
public int Value { get; }
public IntegerMonoid(int value)
{
Value = value;
}
public IntegerMonoid AssociativeBinaryOperation(IntegerMonoid x)
=> new IntegerMonoid(Value + x?.Value ?? 0);
}
public interface Monoid<T>
{
T AssociativeBinaryOperation(T x);
}
public static class FoldableMonoid
{
public static T Fold<T>(IEnumerable<T> t) where T : Monoid<T>
=> t.Aggregate(default(T), (x, y) => y.AssociativeBinaryOperation(x));
}