21. S-Expressions & Lisp
When the syntax tree is the syntax
We've spent the entire series building increasingly sophisticated parsers — tokenizers, recursive descent, Pratt parsing, precedence climbing. All that machinery exists because languages like JavaScript and Python have complex, ambiguous grammars with operator precedence, infix notation, and dozens of statement forms.
What if we threw all of that away?
What if the syntax was the tree? No precedence rules. No ambiguity. No special cases. Just parenthesized lists, all the way down. That's the radical idea behind S-expressions, and it's the foundation of Lisp — one of the oldest programming language families still in active use.
What is an S-expression?
An S-expression (short for "symbolic expression") is defined recursively in two cases:
- An atom: a number, a string, or a symbol (a name like
+ordefine) - A list: an opening parenthesis, zero or more S-expressions, and a closing parenthesis
That's the entire grammar. In pseudo-BNF:
expr = atom | '(' expr* ')'
atom = number | string | symbol
Here are some S-expressions:
42 ; atom (number)
hello ; atom (symbol)
(+ 1 2) ; list: the symbol +, then 1, then 2
(define x 10) ; list: define, x, 10
(if (> x 0) x (- 0 x)) ; nested lists
The last example is an if expression. In a C-like language you'd write
x > 0 ? x : -x. In Lisp, the operator always comes first (prefix notation),
and the structure is always a list.
Parsing S-expressions
Because the grammar is so simple, the parser is shockingly small. Here's a complete S-expression parser in about 20 lines:
function parse(tokens) {
let pos = 0;
function next() { return tokens[pos++]; }
function peek() { return tokens[pos]; }
function parseExpr() {
const token = next();
if (token === "(") {
const list = [];
while (peek() !== ")") {
list.push(parseExpr());
}
next(); // consume ')'
return list;
}
// Atom: try to parse as number, otherwise it's a symbol
const num = Number(token);
return isNaN(num) ? token : num;
}
return parseExpr();
}
Compare this to the hundreds of lines we needed for a recursive descent parser that handles infix operators, precedence, and multiple statement types. The S-expression parser doesn't need any of that because the syntax has no ambiguity. Parentheses make the structure completely explicit.
The tokenizer is equally simple — split on whitespace and parentheses:
function tokenize(input) {
const tokens = [];
let i = 0;
while (i < input.length) {
if (input[i] === " " || input[i] === "\n") { i++; continue; }
if (input[i] === "(" || input[i] === ")") {
tokens.push(input[i]); i++; continue;
}
if (input[i] === '"') {
let str = "";
i++; // skip opening quote
while (i < input.length && input[i] !== '"') str += input[i++];
i++; // skip closing quote
tokens.push(`"${str}"`);
continue;
}
let symbol = "";
while (i < input.length && !" \n()".includes(input[i])) {
symbol += input[i++];
}
tokens.push(symbol);
}
return tokens;
}
Together, the tokenizer and parser are about 40 lines. In a C-like language, you'd need 10 times that just for expression parsing.
Code as data
Here's the deep insight that makes Lisp special. When you write:
(+ 1 2)
The parser produces a JavaScript array: ["+", 1, 2]. And when you write:
(define square (lambda (x) (* x x)))
The parser produces: ["define", "square", ["lambda", ["x"], ["*", "x", "x"]]].
The program's abstract syntax tree is a plain data structure — arrays and primitives. This is called homoiconicity: the code has the same representation as the data.
In JavaScript, the AST is a tree of special node objects (BinaryExpr,
CallExpr, etc.) that only the parser and evaluator understand. In Lisp, the
AST is just lists — the same lists you use as a programmer to store data. Programs
can inspect, modify, and generate other programs using the same tools they use
for any other data.
A tiny Lisp evaluator
Let's build a working Lisp evaluator. It handles numbers, symbols, define,
lambda, if, quote, arithmetic, and list operations:
function evaluate(expr, env) {
// Numbers evaluate to themselves
if (typeof expr === "number") return expr;
// Strings (quoted) evaluate to themselves
if (typeof expr === "string" && expr.startsWith('"')) {
return expr.slice(1, -1);
}
// Symbols look up their value in the environment
if (typeof expr === "string") return envGet(env, expr);
// Lists: the first element determines the form
const [head, ...args] = expr;
// Special forms
if (head === "quote") return args[0];
if (head === "if") {
const [test, then, otherwise] = args;
return evaluate(test, env) ? evaluate(then, env)
: evaluate(otherwise, env);
}
if (head === "define") {
const [name, value] = args;
env.vars[name] = evaluate(value, env);
return null;
}
if (head === "lambda") {
const [params, body] = args;
return { params, body, closure: env }; // capture the environment
}
// Function call: evaluate all elements, apply the first to the rest
const fn = evaluate(head, env);
const values = args.map(a => evaluate(a, env));
if (typeof fn === "function") return fn(...values); // built-in
// User-defined lambda
const childEnv = createEnv(fn.closure);
fn.params.forEach((p, i) => childEnv.vars[p] = values[i]);
return evaluate(fn.body, childEnv);
}
The environment is a simple object with a parent pointer — exactly like the environments we built in earlier articles, just in their simplest form:
function createEnv(parent = null) {
return { vars: {}, parent };
}
function envGet(env, name) {
if (name in env.vars) return env.vars[name];
if (env.parent) return envGet(env.parent, name);
throw new Error(`Undefined: ${name}`);
}
Built-in functions
We seed the global environment with arithmetic and list operations:
function makeGlobal() {
const env = createEnv();
env.vars["+"] = (a, b) => a + b;
env.vars["-"] = (a, b) => a - b;
env.vars["*"] = (a, b) => a * b;
env.vars["/"] = (a, b) => a / b;
env.vars["="] = (a, b) => a === b;
env.vars[">"] = (a, b) => a > b;
env.vars["<"] = (a, b) => a < b;
env.vars["car"] = (list) => list[0];
env.vars["cdr"] = (list) => list.slice(1);
env.vars["cons"] = (h, t) => [h, ...t];
env.vars["list"] = (...args) => args;
env.vars["null?"] = (x) => Array.isArray(x) && x.length === 0;
env.vars["print"] = (x) => { console.log(lispStr(x)); return null; };
return env;
}
car returns the first element of a list. cdr returns everything except the
first. cons prepends an element to a list. These three operations — inherited
from the original 1958 Lisp — are enough to build any list structure.
Closures
Because lambda captures the environment at definition time, closures work
naturally:
(define make-adder
(lambda (n)
(lambda (x) (+ n x))))
(define add5 (make-adder 5))
(add5 10) ; => 15
When make-adder is called with n = 5, it returns a lambda whose closure
field points to an environment where n is 5. When that lambda is later called
with x = 10, it looks up n in its captured environment and finds 5. This is
exactly how closures work in every language — but in Lisp, you can see the
mechanism clearly because there's so little syntax obscuring it.
Macros: code that writes code
Here's where homoiconicity pays off. Since code is data, you can write functions that transform code before it's evaluated. These are macros.
Imagine you want an unless form — like if, but with the condition inverted:
(unless (= x 0) (print "not zero"))
In a C-like language, adding new control flow requires modifying the parser and compiler. In Lisp, you write a macro — a function that takes the raw code (unevaluated lists) and rewrites it:
// When we see (unless cond body), rewrite it to (if cond null body)
if (head === "unless") {
const [cond, body] = args;
return evaluate(["if", cond, null, body], env);
}
The macro receives (= x 0) and (print "not zero") as unevaluated data
structures, rearranges them into an if expression, and hands the result back
to the evaluator. The user has effectively added new syntax to the language
without touching the parser.
This is only possible because Lisp code is made of lists, and lists are easy to manipulate. In JavaScript, you'd need to construct AST node objects. In Lisp, you just rearrange arrays. This is why Lisp has historically been the language of choice for language experimentation — the barrier to extending the language is nearly zero.
The tradeoff
Lisp's syntax is minimal to the point of controversy. Everything is a parenthesized list in prefix notation:
;; Lisp
(if (> (* x x) 100) (print "big") (print "small"))
// JavaScript equivalent
if (x * x > 100) { print("big"); } else { print("small"); }
The JavaScript version uses infix operators, operator precedence, curly braces for
blocks, and special if/else keywords. The Lisp version uses none of these —
it's just nested lists. Proponents say this is beautifully uniform. Critics say
the parentheses make it hard to read.
Both sides have a point. Lisp's uniformity makes it trivially parsable and infinitely extensible via macros. But most programmers find infix math and C-style blocks easier to read at a glance. The history of programming languages is largely the story of trying to get the best of both worlds — the extensibility of Lisp with the readability of more conventional syntax.
Historical context
John McCarthy invented Lisp in 1958 at MIT. S-expressions were originally intended as a low-level representation — McCarthy planned to add a more readable syntax later. But programmers started writing S-expressions directly and found they liked it. The "temporary" syntax became permanent.
Lisp is the second-oldest high-level programming language still in active use (after Fortran). Its descendants include Scheme, Common Lisp, Clojure, Racket, and Emacs Lisp. Ideas that originated in Lisp — garbage collection, REPL-driven development, closures, macros, and the idea that code is data — have spread throughout the programming world.
The complete mini-Lisp
Here's the full evaluator assembled into a runnable program. Combined with the tokenizer and parser from earlier, it's about 80 lines of JavaScript that implement a working (if tiny) programming language:
function run(source) {
const tokens = tokenize(source);
const exprs = [];
let pos = { v: 0 };
while (pos.v < tokens.length) {
exprs.push(parseAt(tokens, pos));
}
const env = makeGlobal();
let result = null;
for (const expr of exprs) {
result = evaluate(expr, env);
}
return result;
}
The run function tokenizes the source, parses all top-level expressions,
creates a global environment with built-in functions, and evaluates each
expression in sequence. The last result is returned.
You can define recursive functions:
(define factorial
(lambda (n)
(if (= n 0) 1 (* n (factorial (- n 1))))))
(factorial 10) ; => 3628800
You can build data structures:
(define xs (list 1 2 3 4 5))
(car xs) ; => 1
(cdr xs) ; => (2 3 4 5)
(cons 0 xs) ; => (0 1 2 3 4 5)
And you can write higher-order functions:
(define map
(lambda (f lst)
(if (null? lst)
(list)
(cons (f (car lst)) (map f (cdr lst))))))
(map (lambda (x) (* x x)) (list 1 2 3 4 5))
; => (1 4 9 16 25)
All in about 80 lines of JavaScript. That's the power of minimal syntax — when the language does less, the implementation is simpler, and the programmer's ability to extend it is greater.
Try It Yourself — Mini-Lisp
Type Lisp expressions below. You can use define,
lambda, if, quote, arithmetic
(+, -, *, /), comparison
(=, >, <), and list operations
(car, cdr, cons, list).
Each line is evaluated in the same environment, so definitions persist.