UP | HOME

Tolk Arith

Table of Contents

Definition

tolk/arith is the arithmetic interpreter in tolk. It corresponds to PLAI Ch.2 (parsing) and PLAI Ch.3 (interpretation): parsing s-expressions into an AST and interpreting the AST to a number. It is the first and simplest complete interpreter in tolk.

Language

The arithmetic language supports three expression forms:

  • A number literal (e.g. 32, 3.14)
  • Addition of two expressions: (+ e1 e2)
  • Multiplication of two expressions: (* e1 e2)

Surface syntax is Racket-like s-expressions. A .rkt file with #lang racket header is also accepted.

AST Classes

(defclass ast-node () ())

(defclass num (ast-node)
  ((n :type number :initarg :n)))

(defclass arith-binary-op (ast-node)
  ((op :type function :initarg :op)
   (l  :type ast-node :initarg :l)
   (r  :type ast-node :initarg :r)))

(defclass plus (arith-binary-op) ((op :initform #'+)))

(defclass mult (arith-binary-op) ((op :initform #'*)))

Generic Functions

(parse sexp)
s-expression or pathname → AST (or list of ASTs).
(interpret ast)
AST → number.
(execute sexp-or-pathname)
parse then interpret.

Notable Design Choice: op Slot

Rather than two separate plusC / multC constructors with distinct interpreter cases (as in PLAI), tolk uses a common arith-binary-op superclass with an op slot storing the operator function. This means:

  • One interpret method handles all binary operations.
  • Adding a new operation (e.g. subtraction) requires only a new subclass, not a new interpreter case.

PLAI uses separate plusC and multC constructors with explicit cases in interp. Tolk uses arith-binary-op with a shared interpret method. Both approaches are correct; tolk's is more extensible but deviates from PLAI's presentation.

Tests

All tests pass (as of 2026-05-02):

  • arith-parse: 4/4
  • arith-interpret: 3/3
  • arith-execute: 4/4

Sources

Related