Skip to content

Instantly share code, notes, and snippets.

@yuchiki
Last active December 12, 2018 04:29
Show Gist options
  • Save yuchiki/2d4c0d0cd386a9c91727a04adb36884c to your computer and use it in GitHub Desktop.
Save yuchiki/2d4c0d0cd386a9c91727a04adb36884c to your computer and use it in GitHub Desktop.
if C# 8.0 released
using System;
namespace tree {
static class Program {
static void Main() =>
Console.WriteLine(MyTree.Sum());
static int Sum(this Tree<int> t) =>
t switch {
Leaf<int> leaf => leaf.Value,
Node<int>(var l, var r) => l.Sum() + r.Sum()
};
static Tree<int> MyTree =
new Node<int>(
new Node<int>(
new Leaf<int>(1),
new Node<int>(
new Leaf<int>(2),
new Leaf<int>(3))),
new Node<int>(
new Node<int>(
new Leaf<int>(4),
new Leaf<int>(5)),
new Leaf<int>(6)));
}
abstract class Tree<T> {}
class Leaf<T> : Tree<T> {
public readonly T Value;
public Leaf(T value) => Value = value;
public void Deconstruct(out T value) => value = Value;
}
class Node<T> : Tree<T> {
public readonly Tree<T> Left;
public readonly Tree<T> Right;
public Node(Tree<T> left, Tree<T> right) => (Left, Right) = (left, right);
public void Deconstruct(out Tree<T> left, out Tree<T> right) => (left, right) = (Left, Right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment