Last active
March 14, 2018 05:29
-
-
Save Porges/165134fa041d69e9185e333b8d13d663 to your computer and use it in GitHub Desktop.
multiple implicit conversions using tuple syntax
This file contains hidden or 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
void Main() | |
{ | |
Tree<int> m = (((1, 2), (3, 4)), (5, (6, 7))); | |
Console.WriteLine(m.Sum()); | |
} | |
abstract class Tree<T> : IEnumerable<T> | |
{ | |
class Leaf : Tree<T> | |
{ | |
public Leaf(T value) => Value = value; | |
public T Value { get; } | |
public override IEnumerator<T> GetEnumerator() | |
{ | |
yield return Value; | |
} | |
} | |
class Branch : Tree<T> | |
{ | |
public Branch(Tree<T> left, Tree<T> right) | |
{ | |
Left = left; | |
Right = right; | |
} | |
public Tree<T> Left {get;} | |
public Tree<T> Right {get;} | |
public override IEnumerator<T> GetEnumerator() | |
=> Left.Concat(Right).GetEnumerator(); | |
} | |
public static implicit operator Tree<T>(T it) | |
=> new Leaf(it); | |
public static implicit operator Tree<T>((Tree<T> left, Tree<T> right) it) | |
=> new Branch(it.left, it.right); | |
public abstract IEnumerator<T> GetEnumerator(); | |
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment