A small Scheme interpreter
last modified November 25, 2026 Guile 3.0
An interpreter is a program that runs other programs. Scheme
programs are lists, and Scheme reads lists with one call to
read, so an interpreter for Scheme written in Scheme needs no
parser. Such an interpreter is called a metacircular evaluator:
it implements a language in the language itself. This article builds one in
small steps, from a calculator to a program that runs files with recursive
procedures and closures. The examples are run with GNU Guile 3.0.7.
Evaluating arithmetic
The smallest evaluator handles numbers and the four arithmetic operations. The program to evaluate is a quoted list, as described in the expressions and evaluation article.
(define (evaluate expr)
(cond ((number? expr) expr)
((pair? expr)
(let ((args (map evaluate (cdr expr))))
(case (car expr)
((+) (apply + args))
((-) (apply - args))
((*) (apply * args))
((/) (apply / args))
(else (error "unknown operator" (car expr))))))
(else (error "bad expression" expr))))
(display (evaluate '(+ 1 2)))
(newline)
(display (evaluate '(* (+ 1 2) (- 10 4))))
(newline)
(display (evaluate '(/ 1 (+ 2 4))))
(newline)
A number evaluates to itself. A list is an operation: evaluate
first evaluates the arguments with a recursive call through
map, and then chooses the Guile procedure that matches the
operator symbol. Because the arguments are evaluated before the operation,
nested expressions such as (* (+ 1 2) (- 10 4)) work at any
depth. The evaluator inherits exact rationals from Guile, so the last
expression gives 1/6.
$ guile arithmetic.scm 3 18 1/6
Environments and variables
To support variables, the evaluator needs an environment, which maps names to values. Here an environment is a list of frames, and each frame is a hash table, from the hash tables article. A name is looked up in the first frame, then in the next, so inner frames shadow outer ones.
(define (make-frame names values)
(let ((frame (make-hash-table)))
(for-each (lambda (name value) (hashq-set! frame name value))
names values)
frame))
(define (lookup env name)
(if (null? env)
(error "unbound variable" name)
(let ((handle (hashq-get-handle (car env) name)))
(if handle
(cdr handle)
(lookup (cdr env) name)))))
(define global-env
(list (make-frame '(+ - * / = < > not)
(list + - * / = < > not))))
(define (evaluate expr env)
(cond ((symbol? expr) (lookup env expr))
((pair? expr)
(apply-procedure (evaluate (car expr) env)
(map (lambda (e) (evaluate e env)) (cdr expr))))
(else expr)))
(define (apply-procedure proc args)
(apply proc args))
(define env (cons (make-frame '(width height) '(6 7)) global-env))
(display (evaluate '(* width height) env))
(newline)
(display (evaluate '(< width height) env))
(newline)
(display (evaluate '(+ width (- height 2)) env))
(newline)
(display (evaluate 42 env))
(newline)
make-frame builds a frame from a list of names and a list of
values. lookup searches the frames with
hashq-get-handle, the eq? version of
hash-get-handle; a handle distinguishes a variable bound to
#f from a missing one.
The operators are now ordinary variables in the global environment, bound
to Guile's own procedures, so the case is gone. A symbol
evaluates to its value, a list is a procedure call whose operator is
evaluated like any other expression, and everything else, such as a number,
evaluates to itself. apply-procedure calls the procedure; the
next sections give it more work.
$ guile variables.scm 42 #t 11 42
Special forms
Some expressions must not evaluate all their parts. quote
returns its argument unevaluated, and if evaluates only one of
its branches. These special forms are recognised by their first
symbol before the procedure call rule applies. The environment code moves
into a module, frames.scm, as described in the
modules and libraries article.
(define-module (frames)
#:export (make-frame extend lookup define-variable! set-variable!
primitive-env))
(define (make-frame names values)
(let ((frame (make-hash-table)))
(for-each (lambda (name value) (hashq-set! frame name value))
names values)
frame))
(define (extend env names values)
(cons (make-frame names values) env))
(define (find-binding env name)
(if (null? env)
(error "unbound variable" name)
(let ((handle (hashq-get-handle (car env) name)))
(if handle
handle
(find-binding (cdr env) name)))))
(define (lookup env name)
(cdr (find-binding env name)))
(define (set-variable! env name value)
(set-cdr! (find-binding env name) value))
(define (define-variable! env name value)
(hashq-set! (car env) name value))
(define primitives
(list (cons '+ +) (cons '- -) (cons '* *) (cons '/ /)
(cons '= =) (cons '< <) (cons '> >) (cons 'not not)
(cons 'remainder remainder)
(cons 'car car) (cons 'cdr cdr) (cons 'cons cons)
(cons 'null? null?) (cons 'list list) (cons 'length length)
(cons 'display display) (cons 'newline newline)))
(define (primitive-env)
(list (make-frame (map car primitives) (map cdr primitives))))
The module exports the frame procedures from the previous section and adds
three more. extend puts a new frame in front of an
environment. define-variable! adds a name to the first frame
and set-variable! changes an existing binding; a later section
uses them. primitive-env returns a new global environment with
the primitive procedures, now including list operations and output.
(use-modules (ice-9 match)
(frames))
(define (evaluate expr env)
(match expr
((? symbol?) (lookup env expr))
(('quote datum) datum)
(('if test then else)
(if (evaluate test env)
(evaluate then env)
(evaluate else env)))
((op . args)
(apply (evaluate op env)
(map (lambda (e) (evaluate e env)) args)))
(_ expr)))
(define env (extend (primitive-env) '(x items) '(0 (3 5 8))))
(display (evaluate '(quote (a b c)) env))
(newline)
(display (evaluate '(car (cdr items)) env))
(newline)
(display (evaluate '(if (= x 0) 'zero (/ 10 x)) env))
(newline)
(display (evaluate '(if (null? items) 0 (car items)) env))
(newline)
match, from the pattern
matching article, makes the cases of the evaluator read like the
grammar of the language. The order of the clauses matters: the pattern
('quote datum) must come before (op . args),
which would match any list. The interpreted program writes
'zero, which the reader turns into (quote zero).
The third expression shows why if cannot be a procedure.
x is 0, and if both branches were evaluated first,
(/ 10 x) would fail with a division by zero.
$ guile -L . branching.scm (a b c) 5 zero 3
Procedures
A lambda expression creates a procedure. The evaluator
represents it as a closure: the parameters, the body, and the
environment in which the lambda was evaluated. The closure is
a record, from the records article.
(use-modules (ice-9 match)
(srfi srfi-9)
(frames))
(define-record-type <closure>
(make-closure params body env)
closure?
(params closure-params)
(body closure-body)
(env closure-env))
(define (evaluate expr env)
(match expr
((? symbol?) (lookup env expr))
(('quote datum) datum)
(('if test then else)
(if (evaluate test env)
(evaluate then env)
(evaluate else env)))
(('lambda params . body) (make-closure params body env))
((op . args)
(apply-procedure (evaluate op env)
(map (lambda (e) (evaluate e env)) args)))
(_ expr)))
(define (evaluate-body body env)
(if (null? (cdr body))
(evaluate (car body) env)
(begin
(evaluate (car body) env)
(evaluate-body (cdr body) env))))
(define (apply-procedure proc args)
(cond ((procedure? proc) (apply proc args))
((closure? proc)
(evaluate-body (closure-body proc)
(extend (closure-env proc) (closure-params proc) args)))
(else (error "not a procedure" proc))))
(define env (primitive-env))
(display (evaluate '((lambda (x) (* x x)) 7) env))
(newline)
(display (evaluate '(((lambda (n) (lambda (x) (+ x n))) 10) 5) env))
(newline)
(display (evaluate '((lambda (f x) (f (f x))) (lambda (x) (* x 3)) 5) env))
(newline)
(evaluate '((lambda (a b)
(display (list 'sum (+ a b)))
(newline)
(display (list 'product (* a b)))
(newline))
4 6)
env)
Calling a closure evaluates its body in a new environment: the closure's
own environment extended with a frame that binds the parameters to the
arguments. Because the frame extends the environment of the definition, not
of the call, the interpreted language has lexical scope, as explained in the
closures article. The second example
returns a procedure that still sees n after the outer
procedure has returned.
evaluate-body evaluates the expressions of a body in order and
returns the value of the last one. apply-procedure now handles
both kinds of procedure: Guile procedures from the global environment and
closures created by the interpreted program.
$ guile -L . procedures.scm 49 15 45 (sum 10) (product 24)
A table of special forms
Each new special form adds a clause to evaluate, so the
procedure grows with the language. A different design keeps the special
forms in a hash table that maps a symbol to a handler, a
procedure that takes the expression and the environment. The evaluator
looks up the first symbol of a list in the table; new forms can then be
added from outside, without changing the evaluator.
(define-module (interp)
#:use-module (ice-9 match)
#:use-module (srfi srfi-9)
#:use-module (frames)
#:export (evaluate evaluate-body define-special-form!))
(define-record-type <closure>
(make-closure params body env)
closure?
(params closure-params)
(body closure-body)
(env closure-env))
(define special-forms (make-hash-table))
(define (define-special-form! name handler)
(hashq-set! special-forms name handler))
(define (evaluate expr env)
(cond ((symbol? expr) (lookup env expr))
((not (pair? expr)) expr)
((hashq-ref special-forms (car expr))
=> (lambda (handler) (handler expr env)))
(else
(apply-procedure (evaluate (car expr) env)
(map (lambda (e) (evaluate e env)) (cdr expr))))))
(define (evaluate-body body env)
(if (null? (cdr body))
(evaluate (car body) env)
(begin
(evaluate (car body) env)
(evaluate-body (cdr body) env))))
(define (apply-procedure proc args)
(cond ((procedure? proc) (apply proc args))
((closure? proc)
(evaluate-body (closure-body proc)
(extend (closure-env proc) (closure-params proc) args)))
(else (error "not a procedure" proc))))
(define-special-form! 'quote
(lambda (expr env) (cadr expr)))
(define-special-form! 'if
(lambda (expr env)
(match expr
((_ test then else)
(if (evaluate test env) (evaluate then env) (evaluate else env)))
((_ test then)
(when (evaluate test env) (evaluate then env))))))
(define-special-form! 'lambda
(lambda (expr env) (make-closure (cadr expr) (cddr expr) env)))
(define-special-form! 'begin
(lambda (expr env) (evaluate-body (cdr expr) env)))
The (interp) module holds the evaluator, the closure record,
and the table. The => clause of cond passes
the handler found by hashq-ref to the lambda that calls it.
The module registers four forms with define-special-form!:
quote, if with an optional else branch,
lambda, and begin.
(use-modules (frames)
(interp))
(define env (primitive-env))
(display (evaluate '((lambda (x y) (if (< x y) y x)) 3 8) env))
(newline)
(evaluate '(begin
(display 'one-armed)
(newline)
(if (> 2 1) (display 'yes))
(newline))
env)
(define-special-form! 'unless
(lambda (expr env)
(if (evaluate (cadr expr) env)
#f
(evaluate-body (cddr expr) env))))
(evaluate '(unless (null? '(1 2)) (display 'not-empty) (newline)) env)
The program imports both modules and adds an unless form of
its own. The handler evaluates the body only when the test is false.
Because special forms are looked up before variables, the names in the
table are reserved: an interpreted program cannot use if as a
variable.
$ guile -L . modular.scm 8 one-armed yes not-empty
Definitions and recursion
So far, an interpreted program cannot name its procedures, so it cannot
write a recursive one. The (definitions) module adds
define and set! as special forms.
(define-module (definitions)
#:use-module (ice-9 match)
#:use-module (frames)
#:use-module (interp))
(define-special-form! 'define
(lambda (expr env)
(match expr
((_ (name . params) . body)
(define-variable! env name (evaluate `(lambda ,params ,@body) env)))
((_ name value)
(define-variable! env name (evaluate value env))))))
(define-special-form! 'set!
(lambda (expr env)
(match expr
((_ name value)
(set-variable! env name (evaluate value env))))))
define has two shapes, matched in order. The procedure
shorthand (define (name . params) body ...) is rewritten with
quasiquote into a lambda,
and the value is stored in the first frame of the current environment.
set! finds the existing binding and changes it. The module
exports nothing; importing it registers the handlers.
(use-modules (frames)
(interp)
(definitions))
(define env (primitive-env))
(define (run expr)
(evaluate expr env))
(run '(define (factorial n)
(if (= n 0)
1
(* n (factorial (- n 1))))))
(run '(define (fib n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2))))))
(run '(begin (display (factorial 20)) (newline)))
(run '(begin (display (fib 20)) (newline)))
(run '(define (make-counter)
(define count 0)
(lambda ()
(set! count (+ count 1))
count)))
(run '(define tick (make-counter)))
(run '(begin (tick) (tick) (display (tick)) (newline)))
factorial can call itself because it is defined in the global
frame, and the global frame is in the environment of the closure.
make-counter uses an internal define, which adds
count to the frame of the call, and set! changes
it; each counter created this way has its own count.
$ guile -L . recursion.scm 2432902008176640000 6765 3
Derived forms
Many Scheme forms can be written in terms of others. let is a
lambda applied to the values, and cond is a chain
of if expressions. Such derived forms need no new
evaluation rule: the handler rewrites the expression and evaluates the
result.
(define-module (derived)
#:use-module (ice-9 match)
#:use-module (interp)
#:export (let->lambda cond->if))
(define (let->lambda expr)
(match expr
((_ ((names values) ...) . body)
`((lambda ,names ,@body) ,@values))))
(define (cond->if expr)
(match expr
((_) #f)
((_ ('else . body)) `(begin ,@body))
((_ (test . body) . clauses)
`(if ,test
(begin ,@body)
,(cond->if `(cond ,@clauses))))))
(define-special-form! 'let
(lambda (expr env) (evaluate (let->lambda expr) env)))
(define-special-form! 'cond
(lambda (expr env) (evaluate (cond->if expr) env)))
let->lambda uses the ellipsis pattern
((names values) ...) to split the bindings into a list of
names and a list of values. cond->if turns the first clause
into an if and the remaining clauses, recursively, into its
else branch; a cond with no clause left gives #f. The bodies
are wrapped in begin, so a clause can hold several expressions.
(use-modules (frames)
(interp)
(derived))
(define let-expr
'(let ((x 2) (y 5))
(* x y)))
(define cond-expr
'(cond ((< n 0) 'negative)
((= n 0) 'zero)
(else 'positive)))
(write (let->lambda let-expr))
(newline)
(write (cond->if cond-expr))
(newline)
(define env (primitive-env))
(display (evaluate let-expr env))
(newline)
(for-each (lambda (n)
(display (evaluate cond-expr (extend env '(n) (list n))))
(newline))
'(-4 0 9))
The program prints the rewritten expressions and then evaluates the
originals. The cond expression is evaluated three times, each time in an
environment where n has a different value. This is the same
idea as a macro, described in the
macros with syntax-rules article, but done by
hand in the evaluator.
$ guile -L . expansion.scm ((lambda (x y) (* x y)) 2 5) (if (< n 0) (begin (quote negative)) (if (= n 0) (begin (quote zero)) (begin (quote positive)))) 10 negative zero positive
Running programs from files
The last step turns the modules into a tool: mini.scm reads a
program from a file and evaluates it form by form. Errors in the
interpreted program are reported in one line instead of a Guile backtrace.
(use-modules (ice-9 exceptions)
(frames)
(interp)
(definitions)
(derived))
(define (run-file file-name)
(let ((env (primitive-env)))
(call-with-input-file file-name
(lambda (port)
(let loop ((form (read port)))
(unless (eof-object? form)
(evaluate form env)
(loop (read port))))))))
(define args (command-line))
(when (not (= (length args) 2))
(display "usage: guile -L . mini.scm program.mini")
(newline)
(exit 1))
(guard (e ((error? e)
(display "error: ")
(display (apply format #f (exception-message e)
(exception-irritants e)))
(newline)
(exit 1)))
(run-file (cadr args)))
run-file reads one form at a time with read, as in
the reading input article, and
evaluates it in a single global environment, so later forms see the
definitions of earlier ones. The file name comes from
the command line. guard
catches errors, as shown in the exceptions
article. The message of a Guile error is a format template
with the irritants as its arguments, so apply with
format builds the text.
; primes.mini - a program for the mini interpreter
(define (prime? n)
(define (check d)
(cond ((> (* d d) n) #t)
((= (remainder n d) 0) #f)
(else (check (+ d 1)))))
(if (< n 2) #f (check 2)))
(define (primes-from n limit)
(cond ((> n limit) '())
((prime? n) (cons n (primes-from (+ n 1) limit)))
(else (primes-from (+ n 1) limit))))
(define (map f items)
(if (null? items)
'()
(cons (f (car items)) (map f (cdr items)))))
(display (primes-from 2 50))
(newline)
(let ((small (primes-from 2 20)))
(display (map (lambda (p) (* p p)) small))
(newline))
(define (count-up i n)
(if (= i n) i (count-up (+ i 1) n)))
(display (count-up 0 1000000))
(newline)
The program uses everything the interpreter supports: procedure
definitions, an internal helper, cond, let, a
lambda passed to a map that the program defines
itself, and comments, which read skips. The
.mini extension keeps the file apart from the Guile sources.
count-up loops a million times. It runs in constant space,
because the interpreter calls apply-procedure and the handlers
in tail position, so a tail call in the interpreted program is a tail call
in Guile. Under /usr/bin/time the program peaked at about
12 MB; a non-tail recursion of the same depth took over 700 MB.
$ guile -L . mini.scm primes.mini (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47) (4 9 25 49 121 169 289 361) 1000000
Errors in interpreted programs
A mistake in an interpreted program is caught by the runner. The next program misspells the name of a procedure.
(define (average a b) (/ (+ a b) 2)) (display (average 3 4)) (newline) (display (avrage 5 6)) (newline)
The forms before the error run normally, so 7/2 is printed.
The call to avrage fails in lookup, and the runner
prints the message and exits with status 1. The second program passes an
empty list to car.
(define items '()) (display (length items)) (newline) (display (car items)) (newline)
car is a Guile primitive, so the error comes from Guile, not
from the interpreter. The runner reports it the same way, with Guile's own
message.
$ guile -L . mini.scm typo.mini 7/2 error: unbound variable avrage $ echo $? 1 $ guile -L . mini.scm empty-list.mini 0 error: Wrong type (expecting pair): ()
What is missing
The interpreter is about 170 lines of Scheme in four modules and a runner,
yet it runs recursive programs with closures. A full Scheme needs more: rest
parameters such as (lambda args ...), strings and characters
as primitives, and, or, and named
let as further derived forms, error checks for the wrong
number of arguments, and continuations. Each feature is a new primitive in
frames.scm or a new handler registered with
define-special-form!, and the
unit testing article shows how to keep
such a growing program correct.
Source
The Metacircular Evaluator — Structure and Interpretation of Computer Programs
Pattern Matching — GNU Guile Reference Manual
In this article we have written an interpreter for a subset of Scheme in
Scheme: we have evaluated arithmetic, added environments made of frames,
special forms, procedures with closures, a table of special forms in a
module, definitions and recursion, derived forms, and a runner for program
files with error reports. The closures
article explains the scoping rule that the interpreter implements, and the
pattern matching article covers
match.
Author
List all Scheme tutorials.