Skip to content

Instantly share code, notes, and snippets.

@louthy
Created April 12, 2021 14:26
Show Gist options
  • Save louthy/321d363b21b032d0154ac80e97519115 to your computer and use it in GitHub Desktop.
Save louthy/321d363b21b032d0154ac80e97519115 to your computer and use it in GitHub Desktop.
Ad hoc polymorphism in C#
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var xs = new[] {"one", " ", "two", " ", "three"};
var ys = new[] {1, 2, 3};
var rx = AddAll<MString, string>(xs);
var ry = AddAll<MInt, int>(ys);
Console.WriteLine(rx);
Console.WriteLine(ry);
}
static A AddAll<MA, A>(A[] xs) where MA : struct, Monoid<A>
{
var result = default(MA).Zero;
foreach (var x in xs)
{
result = default(MA).Add(result, x);
}
return result;
}
}
public interface Semigroup<A>
{
A Add(A x, A y);
}
public interface Monoid<A> : Semigroup<A>
{
A Zero { get; }
}
public struct MInt : Monoid<int>
{
public int Add(int x, int y) =>
x + y;
public int Zero =>
0;
}
public struct MString : Monoid<string>
{
public string Add(string x, string y) =>
x + y;
public string Zero =>
"";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment