Compilers and rule engines represent code as a tree of nodes. It's a classic use of a closed hierarchy: the set of node types is fixed, and many operations walk over it. This checkpoint builds a small evaluator that's generic over its number type.
Warm up: recursion over a tree
Each case of the switch calls Eval again for its children. Follow the calls before you press Run.
using System.Diagnostics;
Node tree = new Node.Add(new Node.Num(2), new Node.Mul(new Node.Num(3), new Node.Num(4)));
Console.WriteLine(Eval(tree));
Console.WriteLine(Show(tree));
static int Eval(Node node) => node switch
{
Node.Num num => num.Value,
Node.Add add => Eval(add.Left) + Eval(add.Right),
Node.Mul mul => Eval(mul.Left) * Eval(mul.Right),
_ => throw new UnreachableException(),
};
static string Show(Node node) => node switch
{
Node.Num num => num.Value.ToString(),
Node.Add add => $"({Show(add.Left)} + {Show(add.Right)})",
Node.Mul mul => $"({Show(mul.Left)} * {Show(mul.Right)})",
_ => throw new UnreachableException(),
};
abstract record Node
{
private Node()
{
}
public sealed record Num(int Value) : Node;
public sealed record Add(Node Left, Node Right) : Node;
public sealed record Mul(Node Left, Node Right) : Node;
}Check your prediction
14
(2 + (3 * 4))Tree rewriting
Transformations produce new trees. Because records are immutable, unchanged parts can be shared safely. x * 1 simplifies to x here, and notice that the children are simplified first, so that the rule can fire on what they become.
using System.Diagnostics;
Node tree = new Node.Mul(new Node.Mul(new Node.Num(5), new Node.Num(1)), new Node.Num(1));
Console.WriteLine(Simplify(tree));
static Node Simplify(Node node)
{
if (node is Node.Num)
{
return node;
}
if (node is Node.Mul mul)
{
Node left = Simplify(mul.Left);
Node right = Simplify(mul.Right);
return right is Node.Num { Value: 1 } ? left : new Node.Mul(left, right);
}
throw new UnreachableException();
}
abstract record Node
{
private Node()
{
}
public sealed record Num(int Value) : Node;
public sealed record Mul(Node Left, Node Right) : Node;
}Check your prediction
Num { Value = 5 }Build it yourself
A generic evaluator
Write a closed hierarchy Expr<T> for any T : INumber<T>, with cases Num(T Value), Var(string Name), Bin(char Op, Expr<T> Left, Expr<T> Right) and Neg(Expr<T> Inner). Op is one of +, -, * and /.
Write Eval(Expr<T> expr, IReadOnlyDictionary<string, T> vars), returning Result<T> with Ok<T> and Fail<T> records. It fails with unknown variable y, or division by zero, or unknown operator ^. Failures from child expressions must carry through. Write Show, too.
Print the result of (x + 2) * -3 with x = 4 as int; the same tree with double and x = 0.5; 1 / (x - x), with x = 1; and y + 1.
When it works, it prints the lines below. Each Name { … } line is a record's built-in ToString, so print the record itself rather than formatting it:
Ok { Value = -18 }
Ok { Value = -7.5 }
((x + 2) * -3)
Fail { Error = division by zero }
Fail { Error = unknown variable y }
Fail { Error = unknown operator ^ }using System.Numerics;
Console.WriteLine(Zero<int>());
static T Zero<T>() where T : INumber<T> => T.Zero;Hint 1: the idea
Bin evaluates both children first. If either one failed, it passes that failure on. Only then does it look at the operator, and check for a zero divisor.
Hint 2: a first step
Write Num and Var first, with a test. To check for division by zero in generic code, compare with T.Zero.
Show one solution
#nullable enable
using System.Diagnostics;
using System.Numerics;
Console.WriteLine(Eval(Tree<int>(2), new Dictionary<string, int> { ["x"] = 4 }));
Console.WriteLine(Eval(Tree<double>(2), new Dictionary<string, double> { ["x"] = 0.5 }));
Console.WriteLine(Show(Tree<int>(2)));
var x = new Expr<int>.Var("x");
Console.WriteLine(Eval(new Expr<int>.Bin('/', new Expr<int>.Num(1), new Expr<int>.Bin('-', x, x)), new Dictionary<string, int> { ["x"] = 1 }));
Console.WriteLine(Eval(new Expr<int>.Bin('+', new Expr<int>.Var("y"), new Expr<int>.Num(1)), new Dictionary<string, int>()));
Console.WriteLine(Eval(new Expr<int>.Bin('^', new Expr<int>.Num(1), new Expr<int>.Num(1)), new Dictionary<string, int>()));
static Expr<T> Tree<T>(int two) where T : INumber<T>
{
return new Expr<T>.Bin('*',
new Expr<T>.Bin('+', new Expr<T>.Var("x"), new Expr<T>.Num(T.CreateChecked(two))),
new Expr<T>.Neg(new Expr<T>.Num(T.CreateChecked(3))));
}
static Result<T> Eval<T>(Expr<T> expr, IReadOnlyDictionary<string, T> vars) where T : INumber<T>
{
switch (expr)
{
case Expr<T>.Num num:
return new Ok<T>(num.Value);
case Expr<T>.Var variable:
return vars.TryGetValue(variable.Name, out T? value) ? new Ok<T>(value) : new Fail<T>($"unknown variable {variable.Name}");
case Expr<T>.Neg neg:
return Eval(neg.Inner, vars) is Ok<T> inner ? new Ok<T>(-inner.Value) : Eval(neg.Inner, vars);
case Expr<T>.Bin bin:
Result<T> left = Eval(bin.Left, vars);
if (left is not Ok<T> a)
{
return left;
}
Result<T> right = Eval(bin.Right, vars);
if (right is not Ok<T> b)
{
return right;
}
return bin.Op switch
{
'+' => new Ok<T>(a.Value + b.Value),
'-' => new Ok<T>(a.Value - b.Value),
'*' => new Ok<T>(a.Value * b.Value),
'/' when b.Value == T.Zero => new Fail<T>("division by zero"),
'/' => new Ok<T>(a.Value / b.Value),
_ => new Fail<T>($"unknown operator {bin.Op}"),
};
default:
throw new UnreachableException();
}
}
static string Show<T>(Expr<T> expr) where T : INumber<T> => expr switch
{
Expr<T>.Num num => num.Value.ToString() ?? "",
Expr<T>.Var variable => variable.Name,
Expr<T>.Neg neg => $"-{Show(neg.Inner)}",
Expr<T>.Bin bin => $"({Show(bin.Left)} {bin.Op} {Show(bin.Right)})",
_ => throw new UnreachableException(),
};
abstract record Expr<T> where T : INumber<T>
{
private Expr()
{
}
public sealed record Num(T Value) : Expr<T>;
public sealed record Var(string Name) : Expr<T>;
public sealed record Neg(Expr<T> Inner) : Expr<T>;
public sealed record Bin(char Op, Expr<T> Left, Expr<T> Right) : Expr<T>;
}
abstract record Result<T>;
sealed record Ok<T>(T Value) : Result<T>;
sealed record Fail<T>(string Error) : Result<T>;Ok { Value = -18 }
Ok { Value = -7.5 }
((x + 2) * -3)
Fail { Error = division by zero }
Fail { Error = unknown variable y }
Fail { Error = unknown operator ^ }Look at the Neg case: when the child fails, it evaluates that child a second time. Harmless here, but wasteful, and wrong if evaluation has effects. Rewrite it to store the result in a variable, as Bin does. Code review should catch small things like this.
Completion is saved in this browser only. It does not measure mastery.