Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// this would be a shape/concept/whatever, not an interfae
interface ICommutativeOrdinalThing<T>
{
/// <summary>
/// Commutative addition of things
/// </summary>
T Add(T a, T b); // with proposal, might pick up +
/// <summary>
/// Comparision of the strictly orderable things
/// </summary>
int Compare(T a, T b); // <, >, <=, =>, ==, !=
}
// this would be implicitly written
private struct CommutativeInt : ICommutativeOrdinalThing<int>
{
int ICommutativeOrdinalThing<int>.Add(int a, int b) => a + b;
int ICommutativeOrdinalThing<int>.Compare(int a, int b) => a.CompareTo(b);
}
// this would be implicitly written
private struct CommutativeString : ICommutativeOrdinalThing<string>
{
string ICommutativeOrdinalThing<string>.Add(string a, string b) => a + b; // not commutative
int ICommutativeOrdinalThing<string>.Compare(string a, string b) => a.CompareTo(b);
}
// this wouldn't look like this, but would do the same underneath
private static void CommutativeOperation<T, TImpl>(T a, T b) where TImpl : struct, ICommutativeOrdinalThing<T>
{
TImpl implementation = default;
T aPlusB = implementation.Add(a, b);
T bPlusA = implementation.Add(b, a);
System.Diagnostics.Debug.Assert(implementation.Compare(aPlusB, bPlusA) == 0);
}
public static void Main(string[] args)
{
CommutativeOperation<int, CommutativeInt>(1, 2);
CommutativeOperation<string, CommutativeString>("Hello", "Goodbye");
// with proposal, call-site might look like this:
//CommutativeOperation(1, 2);
//CommutativeOperation("Hello", "Goodbye");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.