{"id":"6b093dc291bd8fbaf2a0c8dc","slug":"pricing-formula-visitor","title":"Pricing formula visitor","summary":"A pricing formula tree and three operations on it – evaluation, printing and simplification – as visitors. A new operation leaves the node classes untouched.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"hard","topics":["visitor"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["visitor","double-dispatch","expression-tree","composite","behavioral"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** One operation over the formula tree = one visitor. */\ninterface ExprVisitor<R> {\n  visitNum(node: Num): R;\n  visitVar(node: Var): R;\n  visitAdd(node: Add): R;\n  visitMul(node: Mul): R;\n}\n\ninterface Expr {\n  /** Double dispatch: the node calls the visit method for its own type, passing itself. */\n  accept<R>(visitor: ExprVisitor<R>): R;\n}\n\nclass Num implements Expr {\n  constructor(readonly value: number) {}\n\n  accept<R>(visitor: ExprVisitor<R>): R {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\nclass Var implements Expr {\n  constructor(readonly name: string) {}\n\n  accept<R>(visitor: ExprVisitor<R>): R {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\nclass Add implements Expr {\n  constructor(\n    readonly left: Expr,\n    readonly right: Expr,\n  ) {}\n\n  accept<R>(visitor: ExprVisitor<R>): R {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\nclass Mul implements Expr {\n  constructor(\n    readonly left: Expr,\n    readonly right: Expr,\n  ) {}\n\n  accept<R>(visitor: ExprVisitor<R>): R {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\n/** Computes the value; an unknown variable → Error('Unknown variable: <name>'). */\nclass Evaluator implements ExprVisitor<number> {\n  constructor(private readonly variables: Record<string, number>) {}\n\n  visitNum(node: Num): number {\n    throw new Error('Not implemented');\n  }\n  visitVar(node: Var): number {\n    throw new Error('Not implemented');\n  }\n  visitAdd(node: Add): number {\n    throw new Error('Not implemented');\n  }\n  visitMul(node: Mul): number {\n    throw new Error('Not implemented');\n  }\n}\n\n/** Every operation in parentheses: \"((price * qty) + shipping)\"; numbers as String(value) – 2, 1.25. */\nclass Printer implements ExprVisitor<string> {\n  visitNum(node: Num): string {\n    throw new Error('Not implemented');\n  }\n  visitVar(node: Var): string {\n    throw new Error('Not implemented');\n  }\n  visitAdd(node: Add): string {\n    throw new Error('Not implemented');\n  }\n  visitMul(node: Mul): string {\n    throw new Error('Not implemented');\n  }\n}\n\n/**\n * Returns a NEW, simplified tree (children first): Num op Num → Num, x + 0 → x, 0 + x → x,\n * x * 1 → x, 1 * x → x, x * 0 → 0, 0 * x → 0. The original tree stays unchanged.\n */\nclass Simplifier implements ExprVisitor<Expr> {\n  visitNum(node: Num): Expr {\n    throw new Error('Not implemented');\n  }\n  visitVar(node: Var): Expr {\n    throw new Error('Not implemented');\n  }\n  visitAdd(node: Add): Expr {\n    throw new Error('Not implemented');\n  }\n  visitMul(node: Mul): Expr {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"// price * qty + shipping\nconst pricingFormula = () => new Add(new Mul(new Var('price'), new Var('qty')), new Var('shipping'));\nconst show = (expr) => expr.accept(new Printer());\n\ntest('accept() calls the visit method of its own node type', () => {\n  const spy = {\n    visitNum: (n) => 'num:' + n.value,\n    visitVar: (v) => 'var:' + v.name,\n    visitAdd: () => 'add',\n    visitMul: () => 'mul',\n  };\n  expect(new Num(2).accept(spy)).toBe('num:2');\n  expect(new Var('qty').accept(spy)).toBe('var:qty');\n  expect(new Add(new Num(1), new Num(2)).accept(spy)).toBe('add');\n  expect(new Mul(new Num(1), new Num(2)).accept(spy)).toBe('mul');\n  const add = new Add(new Num(1), new Var('x'));\n  expect(add.accept({ ...spy, visitAdd: (node) => node })).toBe(add);\n});\n\ntest('Evaluator computes a pricing formula', () => {\n  expect(pricingFormula().accept(new Evaluator({ price: 20, qty: 3, shipping: 15 }))).toBe(75);\n  expect(new Mul(new Num(1.5), new Var('x')).accept(new Evaluator({ x: 4 }))).toBe(6);\n});\n\ntest('Evaluator rejects an unknown variable', () => {\n  expect(() => pricingFormula().accept(new Evaluator({ price: 20, qty: 3 }))).toThrow('Unknown variable: shipping');\n});\n\ntest('Printer puts every operation in parentheses', () => {\n  expect(show(pricingFormula())).toBe('((price * qty) + shipping)');\n  expect(show(new Add(new Num(2), new Num(1.25)))).toBe('(2 + 1.25)');\n});\n\ntest('a new operation is just a new visitor', () => {\n  class VariableCollector {\n    visitNum() { return []; }\n    visitVar(v) { return [v.name]; }\n    visitAdd(a) { return [...a.left.accept(this), ...a.right.accept(this)]; }\n    visitMul(m) { return [...m.left.accept(this), ...m.right.accept(this)]; }\n  }\n  class NodeCounter {\n    visitNum() { return 1; }\n    visitVar() { return 1; }\n    visitAdd(a) { return 1 + a.left.accept(this) + a.right.accept(this); }\n    visitMul(m) { return 1 + m.left.accept(this) + m.right.accept(this); }\n  }\n  expect(pricingFormula().accept(new VariableCollector())).toEqual(['price', 'qty', 'shipping']);\n  expect(pricingFormula().accept(new NodeCounter())).toBe(5);\n});\n\ntest('Simplifier folds constant subexpressions', () => {\n  expect(show(new Mul(new Add(new Num(2), new Num(3)), new Var('x')).accept(new Simplifier()))).toBe('(5 * x)');\n  expect(show(new Add(new Num(2), new Mul(new Num(3), new Num(4))).accept(new Simplifier()))).toBe('14');\n});\n\ntest('Simplifier removes neutral and absorbing elements', () => {\n  const simplify = (e) => show(e.accept(new Simplifier()));\n  expect(simplify(new Add(new Mul(new Var('x'), new Num(1)), new Num(0)))).toBe('x');\n  expect(simplify(new Mul(new Var('x'), new Num(0)))).toBe('0');\n  expect(simplify(new Add(new Num(0), new Mul(new Num(1), new Var('y'))))).toBe('y');\n  expect(simplify(new Mul(new Add(new Var('a'), new Num(0)), new Var('b')))).toBe('(a * b)');\n});\n\ntest('Simplifier builds a new tree and keeps the meaning', () => {\n  const original = new Add(new Mul(new Var('price'), new Num(1)), new Add(new Num(10), new Num(5)));\n  const simplified = original.accept(new Simplifier());\n  expect(show(simplified)).toBe('(price + 15)');\n  expect(show(original)).toBe('((price * 1) + (10 + 5))');\n  const vars = { price: 20 };\n  expect(simplified.accept(new Evaluator(vars))).toBe(original.accept(new Evaluator(vars)));\n});\n"},{"lang":"javascript","runner":"browser","starter":"// A visitor is any object with visitNum(node), visitVar(node), visitAdd(node), visitMul(node).\n// One operation over the formula tree = one visitor.\n\nclass Num {\n  constructor(value) {\n    this.value = value;\n  }\n\n  /** Double dispatch: the node calls the visit method for its own type, passing itself. */\n  accept(visitor) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\nclass Var {\n  constructor(name) {\n    this.name = name;\n  }\n\n  accept(visitor) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\nclass Add {\n  constructor(left, right) {\n    this.left = left;\n    this.right = right;\n  }\n\n  accept(visitor) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\nclass Mul {\n  constructor(left, right) {\n    this.left = left;\n    this.right = right;\n  }\n\n  accept(visitor) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\n/** Computes the value; an unknown variable → Error('Unknown variable: <name>'). */\nclass Evaluator {\n  constructor(variables) {\n    this.variables = variables;\n  }\n\n  visitNum(node) { throw new Error('Not implemented'); }\n  visitVar(node) { throw new Error('Not implemented'); }\n  visitAdd(node) { throw new Error('Not implemented'); }\n  visitMul(node) { throw new Error('Not implemented'); }\n}\n\n/** Every operation in parentheses: \"((price * qty) + shipping)\"; numbers as String(value) – 2, 1.25. */\nclass Printer {\n  visitNum(node) { throw new Error('Not implemented'); }\n  visitVar(node) { throw new Error('Not implemented'); }\n  visitAdd(node) { throw new Error('Not implemented'); }\n  visitMul(node) { throw new Error('Not implemented'); }\n}\n\n/**\n * Returns a NEW, simplified tree (children first): Num op Num → Num, x + 0 → x, 0 + x → x,\n * x * 1 → x, 1 * x → x, x * 0 → 0, 0 * x → 0. The original tree stays unchanged.\n */\nclass Simplifier {\n  visitNum(node) { throw new Error('Not implemented'); }\n  visitVar(node) { throw new Error('Not implemented'); }\n  visitAdd(node) { throw new Error('Not implemented'); }\n  visitMul(node) { throw new Error('Not implemented'); }\n}\n","testCount":8,"tests":"// price * qty + shipping\nconst pricingFormula = () => new Add(new Mul(new Var('price'), new Var('qty')), new Var('shipping'));\nconst show = (expr) => expr.accept(new Printer());\n\ntest('accept() calls the visit method of its own node type', () => {\n  const spy = {\n    visitNum: (n) => 'num:' + n.value,\n    visitVar: (v) => 'var:' + v.name,\n    visitAdd: () => 'add',\n    visitMul: () => 'mul',\n  };\n  expect(new Num(2).accept(spy)).toBe('num:2');\n  expect(new Var('qty').accept(spy)).toBe('var:qty');\n  expect(new Add(new Num(1), new Num(2)).accept(spy)).toBe('add');\n  expect(new Mul(new Num(1), new Num(2)).accept(spy)).toBe('mul');\n  const add = new Add(new Num(1), new Var('x'));\n  expect(add.accept({ ...spy, visitAdd: (node) => node })).toBe(add);\n});\n\ntest('Evaluator computes a pricing formula', () => {\n  expect(pricingFormula().accept(new Evaluator({ price: 20, qty: 3, shipping: 15 }))).toBe(75);\n  expect(new Mul(new Num(1.5), new Var('x')).accept(new Evaluator({ x: 4 }))).toBe(6);\n});\n\ntest('Evaluator rejects an unknown variable', () => {\n  expect(() => pricingFormula().accept(new Evaluator({ price: 20, qty: 3 }))).toThrow('Unknown variable: shipping');\n});\n\ntest('Printer puts every operation in parentheses', () => {\n  expect(show(pricingFormula())).toBe('((price * qty) + shipping)');\n  expect(show(new Add(new Num(2), new Num(1.25)))).toBe('(2 + 1.25)');\n});\n\ntest('a new operation is just a new visitor', () => {\n  class VariableCollector {\n    visitNum() { return []; }\n    visitVar(v) { return [v.name]; }\n    visitAdd(a) { return [...a.left.accept(this), ...a.right.accept(this)]; }\n    visitMul(m) { return [...m.left.accept(this), ...m.right.accept(this)]; }\n  }\n  class NodeCounter {\n    visitNum() { return 1; }\n    visitVar() { return 1; }\n    visitAdd(a) { return 1 + a.left.accept(this) + a.right.accept(this); }\n    visitMul(m) { return 1 + m.left.accept(this) + m.right.accept(this); }\n  }\n  expect(pricingFormula().accept(new VariableCollector())).toEqual(['price', 'qty', 'shipping']);\n  expect(pricingFormula().accept(new NodeCounter())).toBe(5);\n});\n\ntest('Simplifier folds constant subexpressions', () => {\n  expect(show(new Mul(new Add(new Num(2), new Num(3)), new Var('x')).accept(new Simplifier()))).toBe('(5 * x)');\n  expect(show(new Add(new Num(2), new Mul(new Num(3), new Num(4))).accept(new Simplifier()))).toBe('14');\n});\n\ntest('Simplifier removes neutral and absorbing elements', () => {\n  const simplify = (e) => show(e.accept(new Simplifier()));\n  expect(simplify(new Add(new Mul(new Var('x'), new Num(1)), new Num(0)))).toBe('x');\n  expect(simplify(new Mul(new Var('x'), new Num(0)))).toBe('0');\n  expect(simplify(new Add(new Num(0), new Mul(new Num(1), new Var('y'))))).toBe('y');\n  expect(simplify(new Mul(new Add(new Var('a'), new Num(0)), new Var('b')))).toBe('(a * b)');\n});\n\ntest('Simplifier builds a new tree and keeps the meaning', () => {\n  const original = new Add(new Mul(new Var('price'), new Num(1)), new Add(new Num(10), new Num(5)));\n  const simplified = original.accept(new Simplifier());\n  expect(show(simplified)).toBe('(price + 15)');\n  expect(show(original)).toBe('((price * 1) + (10 + 5))');\n  const vars = { price: 20 };\n  expect(simplified.accept(new Evaluator(vars))).toBe(original.accept(new Evaluator(vars)));\n});\n"},{"lang":"python","runner":"browser","starter":"from abc import ABC, abstractmethod\nfrom dataclasses import dataclass\n\n\nclass ExprVisitor(ABC):\n    \"\"\"One operation over the formula tree = one visitor.\"\"\"\n\n    @abstractmethod\n    def visit_num(self, node: \"Num\"): ...\n\n    @abstractmethod\n    def visit_var(self, node: \"Var\"): ...\n\n    @abstractmethod\n    def visit_add(self, node: \"Add\"): ...\n\n    @abstractmethod\n    def visit_mul(self, node: \"Mul\"): ...\n\n\n@dataclass(frozen=True)\nclass Num:\n    value: float\n\n    def accept(self, visitor: ExprVisitor):\n        \"\"\"Double dispatch: the node calls the visit method for its own type, passing itself.\"\"\"\n        raise NotImplementedError  # TODO\n\n\n@dataclass(frozen=True)\nclass Var:\n    name: str\n\n    def accept(self, visitor: ExprVisitor):\n        raise NotImplementedError  # TODO\n\n\n@dataclass(frozen=True)\nclass Add:\n    left: object\n    right: object\n\n    def accept(self, visitor: ExprVisitor):\n        raise NotImplementedError  # TODO\n\n\n@dataclass(frozen=True)\nclass Mul:\n    left: object\n    right: object\n\n    def accept(self, visitor: ExprVisitor):\n        raise NotImplementedError  # TODO\n\n\nclass Evaluator(ExprVisitor):\n    \"\"\"Computes the value; an unknown variable → ValueError('Unknown variable: <name>').\"\"\"\n\n    def __init__(self, variables: dict[str, float]):\n        self.variables = variables\n\n    def visit_num(self, node):\n        raise NotImplementedError\n\n    def visit_var(self, node):\n        raise NotImplementedError\n\n    def visit_add(self, node):\n        raise NotImplementedError\n\n    def visit_mul(self, node):\n        raise NotImplementedError\n\n\nclass Printer(ExprVisitor):\n    \"\"\"Every operation in parentheses: '((price * qty) + shipping)'; whole numbers without '.0' – 2, 1.25.\"\"\"\n\n    def visit_num(self, node):\n        raise NotImplementedError\n\n    def visit_var(self, node):\n        raise NotImplementedError\n\n    def visit_add(self, node):\n        raise NotImplementedError\n\n    def visit_mul(self, node):\n        raise NotImplementedError\n\n\nclass Simplifier(ExprVisitor):\n    \"\"\"Returns a NEW, simplified tree (children first): Num op Num → Num, x + 0 → x, 0 + x → x,\n    x * 1 → x, 1 * x → x, x * 0 → 0, 0 * x → 0. The original tree stays unchanged.\"\"\"\n\n    def visit_num(self, node):\n        raise NotImplementedError\n\n    def visit_var(self, node):\n        raise NotImplementedError\n\n    def visit_add(self, node):\n        raise NotImplementedError\n\n    def visit_mul(self, node):\n        raise NotImplementedError\n","testCount":8,"tests":"def pricing_formula():\n    # price * qty + shipping\n    return Add(Mul(Var(\"price\"), Var(\"qty\")), Var(\"shipping\"))\n\n\ndef show(expr):\n    return expr.accept(Printer())\n\n\ndef test_accept_calls_the_visit_method_of_its_own_node_type():\n    class Spy(ExprVisitor):\n        def visit_num(self, node):\n            return f\"num:{node.value}\"\n\n        def visit_var(self, node):\n            return f\"var:{node.name}\"\n\n        def visit_add(self, node):\n            return node\n\n        def visit_mul(self, node):\n            return \"mul\"\n\n    add = Add(Num(1), Var(\"x\"))\n    assert Num(2).accept(Spy()) == \"num:2\"\n    assert Var(\"qty\").accept(Spy()) == \"var:qty\"\n    assert add.accept(Spy()) is add, \"the node must pass itself to the visitor\"\n    assert Mul(Num(1), Num(2)).accept(Spy()) == \"mul\"\n\n\ndef test_evaluator_computes_a_pricing_formula():\n    got = pricing_formula().accept(Evaluator({\"price\": 20, \"qty\": 3, \"shipping\": 15}))\n    assert got == 75, f\"expected 75, got {got}\"\n    got = Mul(Num(1.5), Var(\"x\")).accept(Evaluator({\"x\": 4}))\n    assert got == 6, f\"expected 6, got {got}\"\n\n\ndef test_evaluator_rejects_an_unknown_variable():\n    with raises(ValueError, match=\"Unknown variable: shipping\"):\n        pricing_formula().accept(Evaluator({\"price\": 20, \"qty\": 3}))\n\n\ndef test_printer_puts_every_operation_in_parentheses():\n    got = show(pricing_formula())\n    assert got == \"((price * qty) + shipping)\", f\"got {got!r}\"\n    got = show(Add(Num(2), Num(1.25)))\n    assert got == \"(2 + 1.25)\", f\"got {got!r}\"\n\n\ndef test_a_new_operation_is_just_a_new_visitor():\n    class VariableCollector(ExprVisitor):\n        def visit_num(self, node):\n            return []\n\n        def visit_var(self, node):\n            return [node.name]\n\n        def visit_add(self, node):\n            return node.left.accept(self) + node.right.accept(self)\n\n        def visit_mul(self, node):\n            return node.left.accept(self) + node.right.accept(self)\n\n    class NodeCounter(ExprVisitor):\n        def visit_num(self, node):\n            return 1\n\n        def visit_var(self, node):\n            return 1\n\n        def visit_add(self, node):\n            return 1 + node.left.accept(self) + node.right.accept(self)\n\n        def visit_mul(self, node):\n            return 1 + node.left.accept(self) + node.right.accept(self)\n\n    got = pricing_formula().accept(VariableCollector())\n    assert got == [\"price\", \"qty\", \"shipping\"], f\"got {got}\"\n    assert pricing_formula().accept(NodeCounter()) == 5\n\n\ndef test_simplifier_folds_constant_subexpressions():\n    got = show(Mul(Add(Num(2), Num(3)), Var(\"x\")).accept(Simplifier()))\n    assert got == \"(5 * x)\", f\"got {got!r}\"\n    got = show(Add(Num(2), Mul(Num(3), Num(4))).accept(Simplifier()))\n    assert got == \"14\", f\"got {got!r}\"\n\n\ndef test_simplifier_removes_neutral_and_absorbing_elements():\n    def simplify(e):\n        return e.accept(Simplifier())\n\n    assert simplify(Add(Mul(Var(\"x\"), Num(1)), Num(0))) == Var(\"x\")\n    assert simplify(Mul(Var(\"x\"), Num(0))) == Num(0)\n    assert simplify(Add(Num(0), Mul(Num(1), Var(\"y\")))) == Var(\"y\")\n    got = show(simplify(Mul(Add(Var(\"a\"), Num(0)), Var(\"b\"))))\n    assert got == \"(a * b)\", f\"got {got!r}\"\n\n\ndef test_simplifier_builds_a_new_tree_and_keeps_the_meaning():\n    original = Add(Mul(Var(\"price\"), Num(1)), Add(Num(10), Num(5)))\n    simplified = original.accept(Simplifier())\n    assert show(simplified) == \"(price + 15)\", f\"got {show(simplified)!r}\"\n    assert show(original) == \"((price * 1) + (10 + 5))\", \"the original tree must not change\"\n    variables = {\"price\": 20}\n    assert simplified.accept(Evaluator(variables)) == original.accept(Evaluator(variables))\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\nusing System.Globalization;\n\n/// <summary>One operation over the formula tree = one visitor.</summary>\npublic interface IExprVisitor<T>\n{\n    T VisitNum(Num node);\n    T VisitVar(Var node);\n    T VisitAdd(Add node);\n    T VisitMul(Mul node);\n}\n\npublic interface IExpr\n{\n    /// <summary>Double dispatch: the node calls the visit method for its own type, passing itself.</summary>\n    T Accept<T>(IExprVisitor<T> visitor);\n}\n\npublic sealed class Num : IExpr\n{\n    public Num(double value) { Value = value; }\n    public double Value { get; }\n\n    public T Accept<T>(IExprVisitor<T> visitor)\n    {\n        throw new NotImplementedException(); // TODO\n    }\n}\n\npublic sealed class Var : IExpr\n{\n    public Var(string name) { Name = name; }\n    public string Name { get; }\n\n    public T Accept<T>(IExprVisitor<T> visitor)\n    {\n        throw new NotImplementedException(); // TODO\n    }\n}\n\npublic sealed class Add : IExpr\n{\n    public Add(IExpr left, IExpr right) { Left = left; Right = right; }\n    public IExpr Left { get; }\n    public IExpr Right { get; }\n\n    public T Accept<T>(IExprVisitor<T> visitor)\n    {\n        throw new NotImplementedException(); // TODO\n    }\n}\n\npublic sealed class Mul : IExpr\n{\n    public Mul(IExpr left, IExpr right) { Left = left; Right = right; }\n    public IExpr Left { get; }\n    public IExpr Right { get; }\n\n    public T Accept<T>(IExprVisitor<T> visitor)\n    {\n        throw new NotImplementedException(); // TODO\n    }\n}\n\n/// <summary>Computes the value; an unknown variable → KeyNotFoundException(\"Unknown variable: name\").</summary>\npublic class Evaluator : IExprVisitor<double>\n{\n    private readonly IDictionary<string, double> variables;\n\n    public Evaluator(IDictionary<string, double> variables) { this.variables = variables; }\n\n    public double VisitNum(Num node) { throw new NotImplementedException(); }\n    public double VisitVar(Var node) { throw new NotImplementedException(); }\n    public double VisitAdd(Add node) { throw new NotImplementedException(); }\n    public double VisitMul(Mul node) { throw new NotImplementedException(); }\n}\n\n/// <summary>Every operation in parentheses: \"((price * qty) + shipping)\"; numbers with the invariant culture – 2, 1.25.</summary>\npublic class Printer : IExprVisitor<string>\n{\n    public string VisitNum(Num node) { throw new NotImplementedException(); }\n    public string VisitVar(Var node) { throw new NotImplementedException(); }\n    public string VisitAdd(Add node) { throw new NotImplementedException(); }\n    public string VisitMul(Mul node) { throw new NotImplementedException(); }\n}\n\n/// <summary>\n/// Returns a NEW, simplified tree (children first): Num op Num → Num, x + 0 → x, 0 + x → x,\n/// x * 1 → x, 1 * x → x, x * 0 → 0, 0 * x → 0. The original tree stays unchanged.\n/// </summary>\npublic class Simplifier : IExprVisitor<IExpr>\n{\n    public IExpr VisitNum(Num node) { throw new NotImplementedException(); }\n    public IExpr VisitVar(Var node) { throw new NotImplementedException(); }\n    public IExpr VisitAdd(Add node) { throw new NotImplementedException(); }\n    public IExpr VisitMul(Mul node) { throw new NotImplementedException(); }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"import java.util.Map;\n\n/** One operation over the formula tree = one visitor. */\ninterface ExprVisitor<R> {\n    R visitNum(Num node);\n    R visitVar(Var node);\n    R visitAdd(Add node);\n    R visitMul(Mul node);\n}\n\ninterface Expr {\n    /** Double dispatch: the node calls the visit method for its own type, passing itself. */\n    <R> R accept(ExprVisitor<R> visitor);\n}\n\nfinal class Num implements Expr {\n    final double value;\n    Num(double value) { this.value = value; }\n\n    @Override\n    public <R> R accept(ExprVisitor<R> visitor) {\n        throw new UnsupportedOperationException(\"Not implemented\"); // TODO\n    }\n}\n\nfinal class Var implements Expr {\n    final String name;\n    Var(String name) { this.name = name; }\n\n    @Override\n    public <R> R accept(ExprVisitor<R> visitor) {\n        throw new UnsupportedOperationException(\"Not implemented\"); // TODO\n    }\n}\n\nfinal class Add implements Expr {\n    final Expr left;\n    final Expr right;\n    Add(Expr left, Expr right) { this.left = left; this.right = right; }\n\n    @Override\n    public <R> R accept(ExprVisitor<R> visitor) {\n        throw new UnsupportedOperationException(\"Not implemented\"); // TODO\n    }\n}\n\nfinal class Mul implements Expr {\n    final Expr left;\n    final Expr right;\n    Mul(Expr left, Expr right) { this.left = left; this.right = right; }\n\n    @Override\n    public <R> R accept(ExprVisitor<R> visitor) {\n        throw new UnsupportedOperationException(\"Not implemented\"); // TODO\n    }\n}\n\n/** Computes the value; an unknown variable → IllegalArgumentException(\"Unknown variable: name\"). */\nclass Evaluator implements ExprVisitor<Double> {\n    private final Map<String, Double> variables;\n    Evaluator(Map<String, Double> variables) { this.variables = variables; }\n\n    @Override public Double visitNum(Num node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public Double visitVar(Var node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public Double visitAdd(Add node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public Double visitMul(Mul node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/** Every operation in parentheses: \"((price * qty) + shipping)\"; whole numbers without \".0\" – 2, 1.25. */\nclass Printer implements ExprVisitor<String> {\n    @Override public String visitNum(Num node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public String visitVar(Var node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public String visitAdd(Add node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public String visitMul(Mul node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/**\n * Returns a NEW, simplified tree (children first): Num op Num → Num, x + 0 → x, 0 + x → x,\n * x * 1 → x, 1 * x → x, x * 0 → 0, 0 * x → 0. The original tree stays unchanged.\n */\nclass Simplifier implements ExprVisitor<Expr> {\n    @Override public Expr visitNum(Num node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public Expr visitVar(Var node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public Expr visitAdd(Add node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public Expr visitMul(Mul node) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\n// Visitor is one operation over the formula tree. Go 1.13 has no generics, so results are interface{}.\ntype Visitor interface {\n\tVisitNum(n Num) interface{}\n\tVisitVar(v Var) interface{}\n\tVisitAdd(a Add) interface{}\n\tVisitMul(m Mul) interface{}\n}\n\n// Expr is a node; Accept calls the visit method for its own type, passing itself (double dispatch).\ntype Expr interface {\n\tAccept(v Visitor) interface{}\n}\n\n// Num is a constant.\ntype Num struct{ Value float64 }\n\n// Var is a named variable.\ntype Var struct{ Name string }\n\n// Add is Left + Right.\ntype Add struct{ Left, Right Expr }\n\n// Mul is Left * Right.\ntype Mul struct{ Left, Right Expr }\n\n// Accept implements Expr.\nfunc (n Num) Accept(v Visitor) interface{} { return nil } // TODO\n\n// Accept implements Expr.\nfunc (x Var) Accept(v Visitor) interface{} { return nil } // TODO\n\n// Accept implements Expr.\nfunc (a Add) Accept(v Visitor) interface{} { return nil } // TODO\n\n// Accept implements Expr.\nfunc (m Mul) Accept(v Visitor) interface{} { return nil } // TODO\n\n// Evaluator computes float64 values; the first unknown variable is remembered in Err\n// as \"unknown variable: <name>\" (the variable then counts as 0).\ntype Evaluator struct {\n\tVars map[string]float64\n\tErr  error\n}\n\n// VisitNum etc. – TODO\nfunc (e *Evaluator) VisitNum(n Num) interface{} { return nil }\nfunc (e *Evaluator) VisitVar(v Var) interface{} { return nil }\nfunc (e *Evaluator) VisitAdd(a Add) interface{} { return nil }\nfunc (e *Evaluator) VisitMul(m Mul) interface{} { return nil }\n\n// Printer returns strings: every operation in parentheses – \"((price * qty) + shipping)\";\n// numbers via strconv.FormatFloat(v, 'f', -1, 64) – 2, 1.25.\ntype Printer struct{}\n\n// VisitNum etc. – TODO\nfunc (p Printer) VisitNum(n Num) interface{} { return nil }\nfunc (p Printer) VisitVar(v Var) interface{} { return nil }\nfunc (p Printer) VisitAdd(a Add) interface{} { return nil }\nfunc (p Printer) VisitMul(m Mul) interface{} { return nil }\n\n// Simplifier returns a NEW Expr (children first): Num op Num → Num, x + 0 → x, 0 + x → x,\n// x * 1 → x, 1 * x → x, x * 0 → 0, 0 * x → 0. The original tree stays unchanged.\ntype Simplifier struct{}\n\n// VisitNum etc. – TODO\nfunc (s Simplifier) VisitNum(n Num) interface{} { return nil }\nfunc (s Simplifier) VisitVar(v Var) interface{} { return nil }\nfunc (s Simplifier) VisitAdd(a Add) interface{} { return nil }\nfunc (s Simplifier) VisitMul(m Mul) interface{} { return nil }\n\n// Evaluate, Print and Simplify are typed wrappers used by the tests (ready, no changes needed).\nfunc Evaluate(e Expr, vars map[string]float64) (float64, error) {\n\tev := &Evaluator{Vars: vars}\n\tvalue, _ := e.Accept(ev).(float64)\n\treturn value, ev.Err\n}\n\nfunc Print(e Expr) string {\n\ts, _ := e.Accept(Printer{}).(string)\n\treturn s\n}\n\nfunc Simplify(e Expr) Expr {\n\ts, _ := e.Accept(Simplifier{}).(Expr)\n\treturn s\n}\n","testCount":8}],"questionCount":null,"xp":40,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.391Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"The shop platform lets the sales team define price formulas such as "},{"type":"text","text":"price * qty + shipping","marks":[{"type":"code"}]},{"type":"text","text":". A parser turns the text into a tree of "},{"type":"text","text":"Num","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Var","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Add","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"Mul","marks":[{"type":"code"}]},{"type":"text","text":" nodes. More and more operations are needed on that tree: computing the result, printing it to the audit log, simplifying it before caching, with validation and SQL export on the roadmap. Adding yet another method to every node class would bloat them quickly. The "},{"type":"text","text":"Visitor","marks":[{"type":"bold"}]},{"type":"text","text":" pattern flips the layout: nodes only have "},{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]},{"type":"text","text":" and every operation is a separate class with one method per node type."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]},{"type":"text","text":" in every node calls the visitor's method for "},{"type":"text","text":"its own","marks":[{"type":"bold"}]},{"type":"text","text":" type and passes itself ("},{"type":"text","text":"visitNum(this)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"visitAdd(this)","marks":[{"type":"code"}]},{"type":"text","text":" and so on) – this is double dispatch."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Evaluator(variables)","marks":[{"type":"code"}]},{"type":"text","text":" computes the value; an unknown variable ends with the error "},{"type":"text","text":"Unknown variable: <name>","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Printer","marks":[{"type":"code"}]},{"type":"text","text":" puts every operation in parentheses: "},{"type":"text","text":"((price * qty) + shipping)","marks":[{"type":"code"}]},{"type":"text","text":"; whole numbers without a fractional part ("},{"type":"text","text":"2","marks":[{"type":"code"}]},{"type":"text","text":", not "},{"type":"text","text":"2.0","marks":[{"type":"code"}]},{"type":"text","text":"), others in the shortest form ("},{"type":"text","text":"1.25","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Simplifier","marks":[{"type":"code"}]},{"type":"text","text":" returns a "},{"type":"text","text":"new","marks":[{"type":"bold"}]},{"type":"text","text":" tree, simplifying from the leaves up:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Num op Num","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"Num","marks":[{"type":"code"}]},{"type":"text","text":" (constant folding),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"x + 0","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"0 + x","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"x * 1","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"1 * x","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"x","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"x * 0","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"0 * x","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"0","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The original tree must not change."}]}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Formula"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Simplified"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"(2 + 3) * x","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"(5 * x)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"(x * 1) + 0","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"x","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"(price * 1) + (10 + 5)","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"(price + 15)","marks":[{"type":"code"}]}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The tests add their own visitors (collecting variable names, counting nodes) – they must work without changes in the node classes. Language differences: Python uses "},{"type":"text","text":"visit_num","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"visit_var","marks":[{"type":"code"}]},{"type":"text","text":"… and "},{"type":"text","text":"ValueError","marks":[{"type":"code"}]},{"type":"text","text":"; C# "},{"type":"text","text":"IExprVisitor<T>","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"KeyNotFoundException","marks":[{"type":"code"}]},{"type":"text","text":"; Java "},{"type":"text","text":"ExprVisitor<R>","marks":[{"type":"code"}]},{"type":"text","text":" with a generic "},{"type":"text","text":"<R> R accept(...)","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"IllegalArgumentException","marks":[{"type":"code"}]},{"type":"text","text":"; in Go (no generics in 1.13) the methods return "},{"type":"text","text":"interface{}","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Evaluator","marks":[{"type":"code"}]},{"type":"text","text":" stores the first error in its "},{"type":"text","text":"Err","marks":[{"type":"code"}]},{"type":"text","text":" field ("},{"type":"text","text":"unknown variable: <name>","marks":[{"type":"code"}]},{"type":"text","text":"), and the ready-made "},{"type":"text","text":"Evaluate","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Print","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"Simplify","marks":[{"type":"code"}]},{"type":"text","text":" functions wrap the visitors."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3f80884893657cca38","slug":"visitor","title":"Visitor: new operations without changing classes"},{"id":"6b08bd3180884893657cc91a","slug":"composite","title":"Composite – trees in which a leaf and a branch look the same"}],"topicsInfo":[{"slug":"visitor","title":"Visitor","group":"behavioral","icon":"footprints"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:26.392Z","updatedAt":"2026-11-27T08:22:26.392Z"}