Created
April 30, 2018 08:55
-
-
Save VisualMelon/171df96392c9525c7806d56bc80066bd to your computer and use it in GitHub Desktop.
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
// 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