(Lispex)sicp.io
4.1 · An evaluator in the language

A program can inspect a program as data.

Once an expression is represented by lists and symbols, an ordinary Scheme procedure can decide what that expression means.

Guiding question

What must an evaluator do to turn expression data into a value?

  • Distinguish source data from the evaluator executing it
  • Dispatch on an operator symbol
  • Evaluate a nested expression recursively

The quoted list is data, so the host evaluator does not apply its leading plus symbol. Our evaluate procedure inspects that symbol and chooses the operation itself.

Numbers evaluate directly. A compound expression asks evaluate to interpret both nested operands before combining their values. The evaluator follows the expression tree one node at a time.

Lispex · SICP sourceScheme-compatible SICP syntax executed by the Lispex SICP profile.
(begin
  (define (evaluate expression)
    (if (number? expression)
        expression
        (let ((operator (car expression))
              (left (cadr expression))
              (right (caddr expression)))
          (cond ((eq? operator '+)
                 (+ (evaluate left) (evaluate right)))
                ((eq? operator '-)
                 (- (evaluate left) (evaluate right)))
                ((eq? operator '*)
                 (* (evaluate left) (evaluate right)))))))
  (evaluate '(+ (* 3 4) (- 10 2))))
Lispex learning runtimeLispex SICP profile 1.0.0
Loading Lispex SICP runtime
Lispex · SICP source519 / 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Visible execution0 / 0 trace events
    This browser result is not a Lispex Vouch record or authority.wasm —
    Expected observation

    The first program interprets the quoted expression and returns 20.

    Trace focus

    Follow evaluate into the two nested operand trees. Each number reaches the direct-value case, while each list reaches an operator decision.

    Try it yourself

    Change the program before you read the hint.

    Add division to the operator cases, then interpret the expression (/ (+ 8 4) 3).

    Show one hint

    The new case has the same recursive shape as addition and multiplication.