Deviopath › TypeScript

Evaluate an Expression Tree

Hard · Parsing

An expression is a tree of nodes described by the discriminated union Expr (see the starter).

Write evaluate(expr, env) that returns the numeric result, where env maps variable names to numbers.

- "num": the number itself.

- "var": the value from env (use only the object's own keys).

- "neg": minus the value of arg.

- "bin": apply op to left and right. "/" is integer division that truncates toward zero (Math.trunc).

- "let": evaluate value, then evaluate body with name bound to that value (it can shadow an outer variable; do not modify env).

Return null if an unknown variable is used or a division by zero happens anywhere.

Next: Trie with Autocomplete