Module 09.1: From Lambda Calculus to S-Expressions¶
In Module 8, we worked with a programming language that had just three kinds of expressions:
variable
(expr expr)
(λ variable . expr)
We learned to compute by applying functions, substituting arguments, and carefully respecting scope. We even used functions to represent things that were not built into the language, including Booleans and numbers.
That was a useful way to investigate the essentials of computation. It would be a cumbersome way to write most everyday programs. Imagine having to express every number as a function that applies another function repeatedly, or having no convenient names for functions that you want to use more than once.
This module begins with a question: How could we make the ideas of lambda calculus into a more usable programming language without giving up their simplicity?
We'll take a first step toward a small, Racket-like language called Raskell, which we'll eventually implement in Haskell. The important new idea is S-expressions: a uniform way to represent both symbolic data and programs.
Many of you met Racket in CS 60. If you haven't used it, or you've forgotten the details, that's fine: this module explains all the Racket we need.
By the end of this module, you should be able to:
- Recognize how anonymous functions and applications correspond across Haskell, lambda calculus, and Racket-like syntax.
- Read simple nested S-expressions and recognize their tree structure.
- Distinguish symbols, literals, lists, and function applications.
- Explain why quoting an expression changes its meaning.
- Predict the behavior of basic list operations and simple lambda applications.
- Distinguish ordinary function calls from special forms, which have their own evaluation rules.
How to use this module
Work through the page independently, answering each Gradescope question in the Module 9.1 Completion assignment as you reach it.
About the examples: We will use syntax from real Racket to illustrate the language we are working toward. Raskell is a smaller teaching language, not a complete implementation of Racket. Some examples, including arithmetic and conditionals, describe the eventual language and will not necessarily work in the initial Raskell starter. We'll clearly identify examples of that kind.
Racket is installed on the CS 131 server. Run racket there to start a REPL, and try any of the Racket examples on this page.
1. We already know the fundamental operation¶
Consider this expression from lambda calculus:
((λx.x) y)
It applies the identity function to y. One β-reduction gives us y.
The same idea appears in Haskell:
(\x -> x) y
and in Racket:
((lambda (x) x) y)
All three expressions say essentially the same thing: define an anonymous function with parameter x, then apply it to y. In all three cases, y must have a binding for the expression to be evaluated as part of a complete program. If we just want a self-contained example, we can use a literal instead:
-- Haskell
(\x -> x) 5
; Racket
((lambda (x) x) 5)
Both evaluate to 5.
Notice what has changed between the lambda-calculus and Racket versions:
- The Greek
λhas become the wordlambda. - The parameter is written inside a parenthesized parameter list,
(x). - We can write a familiar number directly instead of encoding it as a Church numeral.
What has not changed is the fundamental account of computation: we are still defining and applying functions.
In Racket, as in the lc interpreter, we can use meaningful names such as temperature, distance, or next. The single-letter variables we usually write in lambda calculus are a habit of the notation, not a requirement. Either way, names belong to the concrete syntax. They don't change the underlying model of function application.
More than one parameter¶
Recall that the lambda calculus gave us functions that take one argument at a time. To represent a function of two arguments, we could write:
(λx.(λy.x))
A Racket-like language lets us write two parameter names together:
(lambda (x y) x)
We can then apply that function to two arguments:
((lambda (x y) x) 10 20)
which evaluates to 10.
Try it in Racket - nothing to submit
Log in to the CS 131 server and run racket to start the Racket REPL. Type an expression after the > prompt and press Enter:
$ racket
Welcome to Racket v8.10 [cs].
> ((lambda (x y) x) 10 20)
10
> (cons 1 '(2 3))
'(1 2 3)
> (exit)
You can also leave with Ctrl-D.
Notice that the REPL prints a list result with a leading quote, '(1 2 3), and prints a symbol the same way, as in 'a. That's Racket showing you the value as data. Section 4 explains what the quote means.
Use the REPL as you read: whenever you're unsure what a Racket expression does, try it.
This syntax is more convenient, but it is still expressing the familiar idea of binding arguments to parameters and evaluating a function body. In the language we'll implement, functions will be values, and their bindings will be managed by environments and closures, just as we studied earlier in the course.
2. S-expressions: a remarkably regular syntax¶
Consider these pieces of text:
hello
42
#t
()
(a b c)
(a (b c) d)
(+ 1 2)
They are all examples of S-expressions, short for symbolic expressions.
For the small language we are developing, we can understand S-expressions using a simple grammar:
sexpr ::= atom
| '(' sexpr* ')'
atom ::= symbol | integer | boolean
In other words, an S-expression is either:
- An atom, such as a symbol, number, or Boolean; or
- A list of zero or more S-expressions, enclosed in parentheses.
The * means zero or more, just as it did when we read grammars in Module 6.
This is a deliberately small subset of the full Racket reader syntax. For example, full Racket has strings and additional literal forms. We won't need all of that to understand the language we're going to implement.
Atoms¶
A symbol is a name, such as hello, x, or next. Symbols are different from strings: they are used to represent names and symbolic identities. We will encounter this distinction again when we discuss quotation.
An integer literal such as 42 represents a number. A Boolean literal such as #t (true) or #f (false) represents a Boolean value.
The empty list () is an S-expression, too. As data, the empty list is written '() or (quote ()) in Racket. The unquoted text () is not a valid expression to evaluate in ordinary Racket, because an application has no function to apply. This is an early sign that being a valid S-expression and being a valid program to evaluate are different things.
Lists can contain lists¶
Consider:
(a (b c) d)
The top-level list has three elements:
a
(b c)
d
Its second element is itself a two-element list.
We can see the same structure as a tree:
List
├── Symbol a
├── List
│ ├── Symbol b
│ └── Symbol c
└── Symbol d
This is no longer mysterious, given what we've already learned about recursive datatypes and abstract syntax trees. A list can contain smaller lists, which can contain smaller lists, and so on.
Here is a second example, with the nested list in the last position:
Why is this useful for programs?¶
Look at the arithmetic expression:
(+ 1 (* 2 3))
It's just a list containing three S-expressions:
Symbol +
Number 1
List (Symbol *, Number 2, Number 3)
But if we interpret it as a function application, the first element (+) is the operator and the remaining elements are its arguments. The nested list represents another application, (* 2 3).
Because the nesting is explicit, we don't need a separate precedence convention to decide whether to multiply before adding. The structure already says what belongs together.
In Module 6, we studied parsing as the transformation of source text into structured data. Here, the source text is unusually close to the tree structure we want to represent.
Gradescope question: Read an S-expression
Submit this response on Gradescope.
Consider this S-expression:
(mix red (blend blue green) white)
How many elements are in its top-level list? Identify the nested sublist and say how many elements that sublist contains.
3. A few comparisons with Haskell¶
We've spent much of the semester learning Haskell, so it's useful to see familiar computations in the new notation.
| Idea | Haskell | Racket-like syntax |
|---|---|---|
| Anonymous function | \x -> x + 1 |
(lambda (x) (+ x 1)) |
| Apply a function | (\x -> x + 1) 5 |
((lambda (x) (+ x 1)) 5) |
| Add to the front of a list | 1 : [2,3] |
(cons 1 '(2 3)) |
| Map over a list | map (\x -> x + 1) [1,2,3] |
(map (lambda (x) (+ x 1)) '(1 2 3)) |
These Racket examples are all valid in full Racket and illustrate operations we plan to support in Raskell. They are not a promise that every operation already exists in the starter interpreter.
A few things stand out.
First, application in Racket is written by placing the function first and its arguments after it, inside parentheses:
(+ 1 2)
This is prefix notation, as opposed to Haskell's ordinary infix addition:
1 + 2
Second, functions can be used as values in both languages. A function can appear as the operator in a call, or as an argument to another function such as map.
Third, some Racket expressions contain an apostrophe (') before a list:
'(2 3)
That apostrophe is not decoration and is not just a different spelling for Haskell's [ and ]. It is a shorthand for a language feature called quotation.
Quotation is the most important new idea in this module.
4. The same structure can be code or data¶
Compare these expressions:
(+ 1 2)
'(+ 1 2)
They look almost identical. Yet they have very different meanings.
Without quotation: evaluate the expression¶
When the evaluator sees:
(+ 1 2)
it treats the list as an application.
It finds the function named +, evaluates its arguments, and applies the function to obtain:
3
The expression is code: instructions for a computation.
With quotation: return the expression as data¶
The leading apostrophe means that we want the expression itself, rather than its computed result.
The shorthand:
'(+ 1 2)
means the same thing as:
(quote (+ 1 2))
This evaluates to a list value containing the symbol + and the numbers 1 and 2.
Conceptually, its value is:
List [Symbol "+", Number 1, Number 2]
That last line is illustrative Haskell-style notation, not literal Racket output or the exact datatype of our future starter code.
In the quoted expression, nothing performs addition. The + is an element of the data, not an instruction being executed.
Quotation also works on names¶
Consider:
x
If we ask the evaluator to execute this as a program, it looks up the value of the variable x in the current environment. With no binding for x, evaluating it is an error.
But:
'x
returns the symbol x itself. No variable lookup takes place.
This distinction is worth remembering:
x → find what x means
'x → return the symbol x
Quoting nested structures¶
Quotation applies to the entire expression that follows it:
'(a (b c) d)
The result is a list containing the symbol a, a nested list containing symbols b and c, and the symbol d. None of those symbols is looked up as a variable.
Likewise:
'(+ 1 (* 2 3))
is a nested data structure. Neither + nor * is applied.
Parsing is not the same as evaluating¶
In a small Lisp implementation, the parser can recognize a list-shaped structure such as:
(+ 1 2)
Then evaluation determines whether that structure represents a computation or should be returned as data. For (quote e), the evaluator treats e specially instead of evaluating it as an ordinary argument.
The abbreviation 'e can be recognized by the parser and represented internally as something equivalent to (quote e). We do not need to give the apostrophe a new kind of mathematical meaning. It is simply a convenient way to write quote.
This is why people often describe Lisp-family languages as homoiconic (from Greek homo-, "same," and icon, "representation"): a program is written using the same structure, nested lists of symbols and literals, that the language uses for ordinary data. A Racket program is itself an S-expression, so a program can build, inspect, or transform code using the same list operations it uses for any other list.
Gradescope question: Code versus data
Submit this response on Gradescope.
Explain the difference between evaluating:
(* 3 4)
and:
'(* 3 4)
What kind of value does each produce? In the quoted version, is multiplication performed?
5. Lists: build them and take them apart¶
If lists are such a useful representation, we need a few operations for working with them.
You already know these ideas from Haskell:
1 : [2,3] -- [1,2,3]
head [1,2,3] -- 1
tail [1,2,3] -- [2,3]
Racket has the same basic ideas. For our course language, we will use the names cons, first, and rest, which Racket also provides.
You may also run into the older names car (for first) and cdr (for rest, pronounced "could-er"). They come from the original 1950s Lisp implementation on the IBM 704. There, they stood for "Contents of the Address part of Register" and "Contents of the Decrement part of Register," two halves of a machine word. Racket still supports them, and they appear throughout the optional readings at the end of this module, but we won't use them in Raskell.
Constructing a list with cons¶
(cons 'a '(b c))
This constructs a list by putting the symbol a at the front of the existing list (b c).
The result is:
'(a b c)
Notice that each argument has been evaluated:
'aevaluates to the symbola.'(b c)evaluates to the list value containing symbolsbandc.
The cons function combines those resulting values.
We can build the same list one element at a time:
(cons 'a (cons 'b (cons 'c '())))
This corresponds to the familiar recursive list structure (using Haskell characters to stand in for symbols):
'a' : ('b' : ('c' : []))
Inspecting a list¶
The operation first returns the first element:
(first '(a b c))
; 'a
The operation rest returns a list containing everything after the first element:
(rest '(a b c))
; '(b c)
These are behaviors we want our language to support. You will implement rest as a small exercise in the upcoming lab, so we will not look at its Haskell implementation here.
The important point is that these operations work with values, not unevaluated source text. In:
(first (cons 'm '(n)))
the evaluator first computes a list value from the cons call, then passes that list value to first.
Gradescope question: Building and inspecting lists
Submit this response on Gradescope.
Predict the result of this expression in Racket or the eventual Raskell language:
(first (cons 'blue '(green yellow)))
Briefly explain how cons and first work together to produce that result.
6. Anonymous functions are still doing the work¶
The new language has symbols, literal values, and list operations. But its core treatment of functions remains very close to what we studied in lambda calculus.
Consider:
((lambda (x) (cons x '())) 'hello)
Let's evaluate it conceptually.
First, the evaluator encounters an application whose function expression is:
(lambda (x) (cons x '()))
Evaluating the lambda expression produces a function value, usually represented in an interpreter by a closure. Recall from Module 5 that a closure combines function code with the environment in which the function was defined.
Second, the argument expression:
'hello
is evaluated. Because it is quoted, its value is the symbol hello, not the value of a variable named hello.
Third, the function is applied. In its body, x is bound to that symbol value:
x ↦ Symbol hello
Fourth, the body is evaluated using that binding:
(cons x '())
The result is a one-element list:
'(hello)
The same general machinery we used for functions in Module 5 still applies:
function definition → closure
argument → evaluated value
application → extend the closure's environment
body → evaluate in that environment
One difference from our original lambda calculus is that we are using call-by-value for ordinary Raskell function applications. The argument is evaluated before the function body is evaluated. A later section will show why some language forms must behave differently.
Gradescope question: Function application and quotation
Submit this response on Gradescope.
Consider:
((lambda (item) (cons item '())) 'violet)
What value is bound to item when the function body is evaluated? What is the result of the whole expression? Explain why violet is not looked up as a variable.
7. Not every parenthesized form is an ordinary function call¶
By now, we have a useful general rule for applications:
- Evaluate the function expression.
- Evaluate each argument expression.
- Apply the function to the resulting values.
That is how an ordinary call such as this should behave:
(+ 1 2)
But consider what would happen if we treated every parenthesized expression that way.
quote must not evaluate its argument¶
We already know that:
(quote (+ 1 2))
should return the list-shaped representation of (+ 1 2).
If we evaluated (+ 1 2) before giving it to quote, the argument would have become 3. We would have lost the expression that quotation was supposed to preserve.
Therefore, quote needs its own rule: return its argument as data, without evaluating it first.
if must evaluate only one branch¶
Consider this example in full Racket, and in the Raskell language you will eventually implement:
(if #t 10 (quotient 1 0))
The intended result is 10.
The condition is true, so the second branch should never be evaluated. If we evaluated all the pieces before deciding what if means, we would attempt to divide by zero even though that computation should be skipped.
So if also needs a special evaluation rule:
- Evaluate the condition.
- Decide which branch it selects.
- Evaluate only that branch.
An expression such as if or quote is called a special form because its evaluation is governed by a language rule different from ordinary function application.
This distinction matters later when we add cond, and, and or. Their behavior can depend on which subexpressions are evaluated, not just on what values those subexpressions would produce.
The syntax doesn't decide everything¶
Both an ordinary function call and a special form can be written as parenthesized S-expressions:
(+ 1 2)
(quote (+ 1 2))
(if #t 10 20)
Their shapes are similar. Their meanings are determined by the evaluator.
This is an excellent example of why we distinguish syntax from semantics.
Gradescope question: Why special forms are special
Submit this response on Gradescope.
Suppose our interpreter always evaluated every argument before deciding what to do with an expression.
Explain why that strategy would give the wrong behavior for both of these expressions:
(quote (+ 1 2))
(if #t 10 (quotient 1 0))
What must be different about the way these forms are evaluated?
8. What we've gained, and what comes next¶
We began with three primitive forms of lambda calculus:
variable
application
abstraction
We haven't abandoned those ideas. We've made them easier to work with:
- Lambda expressions still define functions.
- Applications still supply arguments to functions.
- Environments and closures still explain how names get their meanings.
- S-expressions provide an unusually simple representation of nested syntax.
- Quotation lets us handle source-like expressions as ordinary data, which works because Lisp-family languages are homoiconic.
- Special forms allow a language to control which expressions get evaluated.
In Module 09.2, we'll make this account precise by looking inside a small interpreter written in Haskell. We'll see how it parses source text, represents S-expressions, creates function values, looks up variables, and evaluates expressions.
The larger assignment will then ask you to extend that interpreter with more familiar language features. Eventually, you'll write and run a substantial program in the language you implemented yourself.
Optional reading: where these ideas came from¶
The ideas in this module have an important history, but the following readings are not required to complete the module, lab, or homework.
- Paul Graham, The Roots of Lisp. Sections 1–2 introduce a compact account of Lisp's primitive operations and function notation; the later discussion constructs an evaluator. Graham's reconstruction is closer than McCarthy's paper to the small-language-building exercise we'll undertake, though it uses Lisp to explain and implement Lisp, whereas we'll use Haskell as our host language.
- John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I (1960). Section 3 introduces S-expressions and basic symbolic operations, and later develops an interpreter. The original paper uses some notation and conventions that differ from modern Racket.
Both readings emphasize a theme we've encountered all semester: a small collection of carefully chosen abstractions can support a surprisingly expressive system.
Finish Module 09.1¶
Before finishing, make sure you've submitted the five Gradescope questions embedded in the page:
- Read an S-expression.
- Code versus data.
- Building and inspecting lists.
- Function application and quotation.
- Why special forms are special.
Gradescope question: Time spent
Submit this response on Gradescope.
Approximately how much time did you spend on this module?
- less than 30 minutes
- 30 - 45 minutes
- 45 - 60 minutes
- 60 - 75 minutes
- 75 - 90 minutes
- more than 90 minutes
Gradescope question: Lingering questions
Submit this response on Gradescope.
What lingering questions or thoughts do you have about this module?