Skip to content

Instantly share code, notes, and snippets.

@VisualMelon
Created April 30, 2018 08:55
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save VisualMelon/171df96392c9525c7806d56bc80066bd to your computer and use it in GitHub Desktop.
// 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