Skip to content

Instantly share code, notes, and snippets.

@Tarmil
Created August 11, 2021 15:22
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 Tarmil/4c13c94ebde137e21e6665646da517dd to your computer and use it in GitHub Desktop.
Save Tarmil/4c13c94ebde137e21e6665646da517dd to your computer and use it in GitHub Desktop.
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