Created
May 8, 2019 06:39
-
-
Save yuchiki/5f73823a60defd31288ff2ae1d599809 to your computer and use it in GitHub Desktop.
In C# 8.0, we can write a function that calculates the sum of a tree as follows:
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
using System; | |
namespace hoge { | |
class Program { | |
static void Main() { | |
var tree = | |
new Node( | |
new Leaf(1), | |
new Node( | |
new Leaf(2), | |
new Leaf(3) | |
)); | |
Console.WriteLine(Sum(tree)); | |
} | |
static int Sum(Tree tree) { | |
switch (tree) { | |
case Leaf leaf: | |
return leaf.Value; | |
case Node node: | |
(var l, var r) = node; | |
return Sum(l) + Sum(r); | |
default: | |
throw new InvalidOperationException(); | |
} | |
} | |
/* | |
// in C# 8.0, Sum can be written as follows: | |
static int Sum(Tree tree) => | |
t switch { | |
Leaf(n) => n, | |
Node(l, r) => Sum(l) + Sum(r) | |
}; | |
*/ | |
} | |
abstract class Tree {} | |
class Leaf : Tree { | |
public int Value { get; } | |
public Leaf(int value) => Value = value; | |
public void Deconstruct(out int value) => value = Value; | |
} | |
class Node : Tree { | |
public Tree Left { get; } | |
public Tree Right { get; } | |
public Node(Tree left, Tree right) => (Left, Right) = (left, right); | |
public void Deconstruct(out Tree left, out Tree right) => (left, right) = (Left, Right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment