Created
August 11, 2021 15:22
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
var coll = Enumerable.Range(1, 10); | |
// We need to repeat "int" here, it can't be implied by IntAdd or IntMul :( | |
Console.WriteLine($"The sum is {AppendMany<IntAdd, int>(coll)}"); | |
Console.WriteLine($"The product is {AppendMany<IntMul, int>(coll)}"); | |
TValue AppendMany<TMonoid, TValue>(IEnumerable<TValue> xs) where TMonoid : IMonoid<TValue> | |
{ | |
var acc = TMonoid.Empty; | |
foreach (var x in xs) | |
{ | |
acc = TMonoid.Append(acc, x); | |
} | |
return acc; | |
} | |
interface IMonoid<TValue> | |
{ | |
static abstract TValue Empty { get; } | |
static abstract TValue Append(TValue x, TValue y); | |
} | |
class IntAdd : IMonoid<int> | |
{ | |
public static int Empty => 0; | |
public static int Append(int x, int y) => x + y; | |
} | |
class IntMul : IMonoid<int> | |
{ | |
public static int Empty => 1; | |
public static int Append(int x, int y) => x * y; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment