How to Design Programs – Free Online Book (Felleisen et al., 2nd Edition) BSCS

BSCS students can read How to Design Programs, Second Edition free online. It is a first programming textbook by Matthias Felleisen, Robert Bruce Findler, Matthew Flatt and Shriram Krishnamurthi, published by MIT Press, and it fits a Programming Fundamentals or Introduction to Computing course. The official site offers no PDF: the authors keep the whole book free to read in the browser, and a printed edition is sold by MIT Press.

The book teaches a method, not a language. You learn a design recipe that starts from data definitions and examples and ends in tests, then apply it to numbers and structures, lists of any length, abstraction with higher-order functions, trees and mutually referential data, algorithms built by recursion, and functions that accumulate knowledge. The programs run in DrRacket using Racket-family teaching languages, so it is a different experience from a C++ course, and this page says plainly what that means for you.

Book Overview

CourseProgramming Fundamentals / Introduction to Program Design
Degree ProgramsBSCS
LevelUniversity / Undergraduate (first year, introductory)
EditionSecond Edition (MIT Press print edition 2018); online version 9.2.0.3, released 28 May 2026
AuthorsMatthias Felleisen, Robert Bruce Findler, Matthew Flatt, Shriram Krishnamurthi
PublisherMIT Press (copyright 2014)
LanguageEnglish
Total Chapters34 chapters in 6 parts, plus a prologue, 5 intermezzos and an epilogue
Exercises528 numbered exercises, including finger exercises and projects
Programming LanguageRacket-family teaching languages (BSL, BSL+, ISL, ISL+) in DrRacket
LicenseCC BY-NC-ND 2.0 — Model: Link-only
FormatFree online book (HTML); no official PDF; printed edition from MIT Press

Chapter List

Prologue: How to Program

Difficulty: Easy · Key topics: DrRacket, Beginning Student Language, prefix arithmetic, define, animate, cond, constant definitions, refactoring

The Prologue is a first hour at the keyboard. You open DrRacket, evaluate prefix arithmetic on numbers, strings, Booleans and images, then define a function and use it to build picture-of-rocket, an image of a rocket on an empty scene. The animate function calls that function on every clock tick, so the picture becomes a movie. A cond expression stops the rocket at the ground, constant definitions replace repeated numbers, and the last fix makes the parameter a time instead of a height. The closing sections tell you that you are a programmer now, then explain why that claim needs the rest of the book.

Key Points:

  • DrRacket has a definitions area for your program and an interactions area where expressions are evaluated.
  • BSL writes operations in prefix form, with parentheses around each use: (+ 1 2).
  • (define (f x) ...) defines a function and (define NAME expr) defines a constant.
  • The function given to animate is called on each clock tick (28 times a second) and returns the next image.
  • Constant definitions must appear before they are used; function definitions can come in any order.
  • Repeating a number such as 60 in many places is called a magic number problem; a named constant fixes it.

Practice Tip: Define WIDTH and HEIGHT, build the scene from them, then change one value and see that only one line of your program changes.

Common Mistake: Passing a clock tick count to code that expects a distance. The Prologue shows such a program working only by accident, so name each parameter after what it really means.

Important Questions:

  • Why replace numbers like 60 and 100 with constant definitions? A request such as a new canvas size then needs one edit instead of many, and the name explains what the number stands for.
  • What does animate do with a function? It calls the function repeatedly with the number of ticks since the start and shows each resulting image as one frame.

Chapters 1-2: Arithmetic; Functions and Programs

Part I: Fixed-Size Data · Difficulty: Easy · Key topics: prefix notation, numbers, strings, 1String, images, Booleans, predicates, function definition, composition, global constants, batch programs

Chapter 1 treats arithmetic as half of programming and introduces the four kinds of atomic data in BSL: numbers, strings, images and Booleans. Each comes with its own operations, such as string-append, overlay and and, and with a predicate like number? that tells you what kind of data you hold. Chapter 2 supplies the algebra half: function definitions, function application, composition of auxiliary functions, and global constants. It explains how DrRacket computes by substituting arguments into a function body, and separates batch programs from interactive ones.

Key Points:

  • An expression is evaluated by first reducing its arguments to values, then applying the operation.
  • Strings are compared with string=?, not =; positions in string-ith start at 0.
  • A 1String is a string of length one, the result of string-ith.
  • Images are values like numbers: circle, rectangle, overlay and place-image come from the 2htdp/image teachpack.
  • Applying a function with the wrong number of arguments is an error.
  • A program is a main function composed of auxiliary functions; every constant named in a problem deserves a constant definition.

Practice Tip: Try (string-ith "hello" 0) and then (string-ith "hello" 5). The second one signals an error because the last valid position is 4.

Common Mistake: Mixing data types in one expression, such as adding a number to a string. Read the red error message and look at the highlighted code instead of rewriting at random.

Important Questions:

  • How does DrRacket evaluate (f (+ 1 1)) when f squares its input? It first reduces the argument to 2, substitutes 2 for the parameter in the body, and computes (* 2 2), which is 4.
  • What is a predicate and why does Chapter 1 end with them? A predicate such as string? or image? answers #true or #false about the kind of a value, so a function can check its input.

Chapter 3: How to Design Programs

Part I: Fixed-Size Data · Difficulty: Medium · Key topics: information and data, data definition, signature, purpose statement, examples, template, check-expect, domain knowledge, world programs

This is the chapter the whole book hangs on. It separates information from the data that represents it, then gives the design recipe for functions: write data definitions, then a signature, purpose statement and header, work through examples, build a template, fill in the body and finally turn the examples into tests. Later sections cover domain knowledge from outside programming, designing programs with several functions and constants, testing with check-expect, and the recipe for world programs built on a state definition, a render function and event handlers. The virtual pet exercises start here.

Key Points:

  • Information is what the problem is about; data is how the program represents it, so every data definition must say how to read the data back.
  • A signature such as Number -> String says what a function consumes and produces; a purpose statement says what it computes.
  • The six steps are data definitions, signature with purpose and header, examples, template, body, and tests.
  • check-expect lines can sit above or below the function; clicking RUN collects and reports them.
  • A world program needs a data definition for the world state, a render function from state to image, and handlers for ticks, keys or the mouse as required.
  • Programmers must learn the language of the problem domain, whether music, biology or mathematics.

Practice Tip: Take any small function and write the signature, purpose statement, header and two check-expect lines first, with a stub body that returns a dummy value. Run it and watch the tests fail before you write the real body.

Common Mistake: Skipping steps because the function looks easy. The chapter says to skip none until the steps feel automatic, since skipped steps cause the silly errors that waste the most time.

Important Questions:

  • What are the steps of the design recipe for functions? Data definitions; signature, purpose statement and header; functional examples; template; function body; tests.
  • What must a programmer supply for big-bang style world programs? A data definition for the state of the world and a rendering function, plus tick, key or mouse handlers when the program needs them.

Chapter 4: Intervals, Enumerations, and Itemizations

Part I: Fixed-Size Data · Difficulty: Medium · Key topics: cond, enumeration, interval, itemization, design with itemizations, finite state worlds

Numbers, strings, images and Booleans are not enough to describe a traffic light or a tax bracket, so this chapter shows how to restrict them. An enumeration lists every allowed piece of data, an interval describes a range of numbers, and an itemization mixes both with other data classes. The chapter works through a UFO descent with a status line, the three-stage sales tax of Tax Land, and a key-event handler. It stresses that the shape of the data definition dictates the shape of the function, then ends with finite state worlds such as a traffic light.

Key Points:

  • An enumeration spells out each member; an interval is a range of numbers; an itemization generalizes both.
  • Use cond when distinct situations come from a data definition and if for a plain either-or.
  • A cond line is called a clause; the number of clauses mirrors the number of items in the data definition.
  • Examples should cover every item and the points where one interval meets the next.
  • A finite state world is drawn as states and arrows in a state-transition diagram and implemented with a data definition for the states.

Practice Tip: Write the UFO status function and test one value in each region plus the exact boundary values. Boundary tests find wrong comparison operators fastest.

Common Mistake: Writing intervals so that a boundary value falls into two clauses or none. State each interval with its endpoints before you write the conditions.

Important Questions:

  • When should you use cond instead of if? Use cond whenever the situations come directly from a data definition with several items; keep if for choosing between exactly two cases.
  • What is the difference between an enumeration and an interval? An enumeration lists a finite number of explicit values, while an interval describes a range of numbers, which could be infinitely many.

Chapters 5-6: Adding Structure; Itemizations and Structures

Part I: Fixed-Size Data · Difficulty: Medium · Key topics: posn, define-struct, selectors, constructors, predicates, universe of data, itemizations of structures, key=?, mouse=?

Chapter 5 starts with a bouncing ball whose position needs two numbers and introduces the built-in posn structure, then the define-struct form that lets you create your own structure types with named fields. It covers computing with structures, the universe of data, designing with structures, world programs with two independent pieces of state, and a graphical one-line editor. Chapter 6 combines the two tools: itemizations whose members are structures, such as the space invader game, mixed worlds, input checking with predicates, and the equality predicates key=? and mouse=?. Chapter 7 is a one-page summary of Part I.

Key Points:

  • (define-struct ball [x y speed-x speed-y]) gives you make-ball, the selectors ball-x and so on, and the predicate ball?.
  • A selector applied to a constructor returns the original field: (posn-x (make-posn 3 4)) is 3.
  • Structure types name their fields and may have any number of them, including zero.
  • A data definition for a structure names the class of data allowed in each field, and the template lists one selector per field.
  • Not every string is a key event, so use key=? and mouse=? instead of string=? to compare events.
  • Chapter 7 asks you to know these terms: structure type definition, data definition, big-bang and event-handling function.

Practice Tip: Define a structure for a pet with a name and a happiness number, make an instance, and select each field in the interactions area before writing any function on it.

Common Mistake: Using one structure type for two different meanings in the same program. Give each meaning its own data definition, as the book does for one-dimensional and two-dimensional balls.

Important Questions:

  • What does one define-struct form create? A constructor, one selector per field and a predicate for the new structure type.
  • Why combine itemizations with structures? Real data is often one of several structure types, such as a game state that is either flying or landed, so the template needs a predicate per item and selectors inside each clause.

Intermezzo 1: Beginning Student Language

Part I: Fixed-Size Data · Difficulty: Medium · Key topics: vocabulary, grammar, meaning, stepper, syntax errors, and/or, structure definitions, tests, error messages

The first intermezzo steps back and defines BSL precisely instead of treating it as a natural language. It gives the vocabulary (literal constants, primitives and variables), a grammar for definitions and expressions in which define, cond and else are marker words, and a meaning in terms of algebra laws that rewrite an expression step by step to a value. It shows how to extend the model for and and or, constant definitions, structure type definitions and test forms, and ends with a catalogue of error messages, each with an explanation and a suggested fix.

Key Points:

  • A primitive is a name BSL already gives a meaning to, such as + or sqrt; a variable has no preassigned meaning.
  • DrRacket signals a syntax error when a phrase does not fit the grammar; some legal phrases still have no meaning.
  • Evaluation applies the laws of arithmetic and algebra: arguments become values, then are substituted into the function body.
  • and and or are keywords, not function applications, so their evaluation rules differ.
  • Test expressions are collected and moved to the end of the program, run in their original order.

Practice Tip: Take a program from Chapter 3 and press the stepper’s Step button. Compare each rewriting step with the one you would do on paper.

Common Mistake: Guessing at a red error message. Find the matching entry in the BSL error message figures and read the suggested fix.

Important Questions:

  • What does the stepper model? A student applying the laws of arithmetic and algebra, so it shows how DrRacket reduces an expression to a value.
  • Why is (and a b) not a normal function application? and is a keyword with its own evaluation rule, so its grammar and meaning must be defined separately.

Chapters 8-9: Lists; Designing with Self-Referential Data Definitions

Part II: Arbitrarily Large Data · Difficulty: Medium · Key topics: list, empty list, cons, first, rest, self-reference, natural recursion, non-empty lists, natural numbers, add1, sub1, Russian dolls

Chapter 8 introduces self-referential data definitions through lists: a list is either the empty list '() or a cons of an item onto a list. It builds lists, explains what '() and cons really are, and designs contains-flatt? for a phone’s contact list, then evaluates it by substitution. Chapter 9 turns this into a design recipe: when a definition refers to itself, the template refers to itself in the same place. Examples include lists of numbers, non-empty lists, natural numbers built with add1, nested Russian dolls, a world that fires shots, and a note on lists and sets.

Key Points:

  • A list is either '() or (cons item list); first and rest take a non-empty list apart.
  • A self-referential definition is valid only if it has at least two clauses and at least one clause does not refer back to it.
  • The template of a function on such data has a cond clause per data clause, and the self-reference becomes a recursive call.
  • A non-empty list definition is useful when the empty case makes no sense, such as the average of temperatures.
  • Natural numbers can be treated like lists: add1 acts as the constructor and sub1 as the selector.

Practice Tip: Design sum for a list of numbers, then run it on a three-item list in the stepper. You will see the empty-list answer being added back one item at a time.

Common Mistake: Writing the recursive clause first and forgetting the base case, or the reverse. The data definition has both clauses, so the template and the function must too.

Important Questions:

  • What two conditions make a self-referential data definition valid? It must have at least two clauses, and at least one clause must not refer back to the class being defined.
  • What is the template for a function on a list of numbers? A cond with one clause for '() and one that uses (first l) and the recursive call (f (rest l)).

Chapters 10-11: More on Lists; Design by Composition

Part II: Arbitrarily Large Data · Difficulty: Medium · Key topics: functions producing lists, structures in lists, files as lists, list function, auxiliary functions, wish lists, sorting

Chapter 10 applies the list recipe in richer settings: a wage* function that produces a list of wages from a list of hours, employee records stored as structures inside lists, text files read with read-file from the 2htdp/batch-io teachpack, and a second look at the graphical editor. Chapter 11 moves to program-level design. It introduces the list function and the BSL+ language level, then lays out design by composition: one function per task, auxiliary functions for every dependency between data definitions, wish lists, a sorting function that inserts items into a sorted rest, and auxiliary functions that solve a more general problem.

Key Points:

  • (list 1 2 3) abbreviates nested cons calls and needs the language level with list abbreviations.
  • A function that produces a list builds its answer with cons in the recursive clause.
  • Lists may hold structures, so the template for the list calls an auxiliary function for the structure.
  • A wish list names the functions you still have to design, each with signature and purpose.
  • Design one template per data definition, and add an auxiliary function wherever one definition points to another.
  • Sorting by insertion needs two functions: one that sorts the rest, and one that inserts the first item into a sorted list.

Practice Tip: Write wage* first with plain numbers, then change the data definition to employee structures and watch which parts of the template change.

Common Mistake: Packing two tasks, such as sorting and inserting, into one function body. The chapter’s rule is one function per task, with a wish list for the rest.

Important Questions:

  • What is a wish list? A list of functions you plan to define later, each recorded with its signature and purpose statement so the main function can use them now.
  • How does the book sort a list of numbers? It sorts the rest of the list recursively and then inserts the first item into the sorted result with a separate auxiliary function.

Chapters 12-13: Projects: Lists

Part II: Arbitrarily Large Data · Difficulty: Hard · Key topics: dictionaries, iTunes data, word games, wish lists, Worm, Tetris, Space War, finite state machines, decomposition

Chapter 12 is a set of extended projects that need everything in Part II. You process a dictionary of words, analyse an exported music library with tracks, dates and association lists, and design arrangements, a function that lists every rearrangement of a word and leads to a deep wish list. Then come three games: Worm (snake), a simplified Tetris and a full Space War with many shots, and finally finite state machines that recognise key sequences. Chapter 13 closes Part II with three lessons about self-reference, decomposition and the practical details of tools such as big-bang.

Key Points:

  • These projects use the 2htdp/batch-io teachpack to read real data from files.
  • Lists of associations model lookup tables such as a dictionary or a music library.
  • arrangements returns the permutations of a word; a word with a repeated letter may produce duplicate strings, which the book accepts.
  • Games reuse the world-program recipe: state definition, render, tick and key handlers.
  • Decomposition helps when the problem names auxiliary tasks, when coding needs a traversal of another large piece of data, or when the general problem is easier.

Practice Tip: Start the word-game exercise on paper: list the wishes for a three-letter word before typing any code. The wish list shows how much work each function really hides.

Common Mistake: Drawing the game before deciding what the world state is. Fix the data definition first, because every handler and the renderer depend on it. Note that Section 12.2 describes exporting from iTunes, which Apple has replaced with the Music app on Mac, so the export steps may differ while the list processing stays the same.

Important Questions:

  • What are the arrangements of a word? All the ways to rearrange its letters, which mathematicians call permutations; the function is built with auxiliary functions that insert one letter everywhere in a word.
  • When does the book recommend decomposing a problem? When the statement mentions auxiliary tasks, when coding calls for a second traversal of arbitrarily large data, or when a more general problem is easier to solve.

Intermezzo 2: Quote, Unquote

Part II: Arbitrarily Large Data · Difficulty: Easy · Key topics: quote, quasiquote, unquote, unquote-splice, lists, S-expressions, XHTML

This short intermezzo introduces the notation Lisp-style languages have used since the late 1950s for writing lists compactly. Quote turns a long list expression into a quoted list, quasiquote with unquote lets you drop computed values into a quoted template, and unquote-splice inserts the items of a list in place. The closing example generates a small web page as nested lists. The chapter also warns that quote hides how lists are built, which is why the book holds it back until you understand cons.

Key Points:

  • '(1 2 3) means the same as (list 1 2 3).
  • Quasiquote lets you write a list template and insert computed values with a comma.
  • Unquote-splice inserts the items of a list instead of the list itself.
  • Quoted notation needs the BSL+ language level or higher.
  • Think of lists as built from cons when designing, not as quoted data.

Practice Tip: Compare a quoted list that contains (+ 1 1) with a quasiquoted one that unquotes it. The first keeps the expression as data, the second computes 2.

Common Mistake: Expecting a quoted list to evaluate the expressions inside it. Quote treats everything inside as data.

Important Questions:

  • What is the difference between quote and quasiquote? Quote treats everything as literal data, while quasiquote allows selected parts to be evaluated with unquote.
  • What does unquote-splice do? It evaluates an expression that produces a list and inserts its items into the surrounding list.

Chapters 14-15: Similarities Everywhere; Designing Abstractions

Part III: Abstraction · Difficulty: Hard · Key topics: similar functions, parameters, parametric data definitions, functions as values, ISL, signatures, single point of control, templates

Part III starts from an observation about the exercises you have already done: many solutions look alike, and copying code is the wrong response. Chapter 14 compares pairs such as contains-dog? and contains-cat?, abstracts by turning the differing literal into a parameter, and then abstracts similar data definitions into parametric ones like [List-of ITEM]. It moves to the Intermediate Student Language, where functions are values that can be passed and returned, and shows how evaluation still follows algebra. Chapter 15 gives the recipe: abstract from examples, describe the result with a general signature, keep a single point of control, and derive abstractions from templates.

Key Points:

  • To abstract is to replace a concrete value with a parameter; do it for functions and for data definitions.
  • [List-of Number] is another name for a list of numbers, so one parametric definition replaces many copies.
  • In ISL a function can be an argument and a name can appear in the first position of an application.
  • A signature is itself a kind of data definition, and a general signature is what makes an abstraction reusable.
  • Single point of control: after abstracting, a mistake is fixed once instead of in every copy.
  • The template for a data definition already exposes the shape many functions share.

Practice Tip: Write two functions that differ in one literal, abstract that literal into a parameter, and redefine both originals in one line each using the new function. Run the old tests unchanged.

Common Mistake: Abstracting two functions that only look similar. If you cannot name a parameter for every difference, the functions are not instances of one abstraction.

Important Questions:

  • What does it mean to abstract a function? Compare two similar definitions, replace each difference with a parameter, and define the originals as uses of the new function.
  • Why is single point of control useful? The shared logic lives in one place, so a bug fix or an improvement reaches every user of the abstraction at once.

Chapters 16-17: Using Abstractions; Nameless Functions

Part III: Abstraction · Difficulty: Hard · Key topics: map, filter, foldr, foldl, build-list, local, lambda, sorting with comparison, functions as data

Chapter 16 is about reuse. It surveys the list abstractions built into ISL, including foldr and foldl that reduce a list to a single value, then adds local definitions so helper functions stay private. It shows that local adds real expressive power, explains evaluation by renaming and lifting local definitions, and gives a recipe for finding a matching abstraction from a signature and purpose statement. Chapter 17 introduces lambda for one-use functions, shows that a function definition abbreviates a constant definition with a lambda, applies it to a general sort, and ends with functions that represent information. Chapter 18 summarises Part III.

Key Points:

  • foldr and foldl reduce a list with a combining function and a starting value, as in (foldr + 0 (list 1 2 3)).
  • (build-list n add1) creates the list 1 to n.
  • A local expression keeps auxiliary definitions private to one function.
  • The evaluator renames the local names to fresh ones, lifts the definitions to the top level, then evaluates the body.
  • (lambda (x) ...) builds a function without naming it.
  • Find the abstraction by writing signature, purpose, example and stub first, then matching them to a known abstraction.

Practice Tip: Take a list function you wrote in Part II, such as a conversion from Fahrenheit to Celsius, and rewrite it with map and a lambda. Check that your old tests still pass.

Common Mistake: Hard-coding a helper that depends on a local variable at the top level. Use local or lambda so the helper can see the variables it needs.

Important Questions:

  • What do foldr and foldl do? Both reduce a list to one value by combining its items with a given function, starting from a given base value, but they traverse from different ends.
  • What is a lambda expression for? It creates a function on the spot, so you can pass a one-time function to an abstraction without defining a named helper.

Intermezzo 3: Scope and Abstraction

Part III: Abstraction · Difficulty: Medium · Key topics: scope, binding occurrence, bound occurrence, ISL loops, pattern matching

Part III used local and lambda informally, and this intermezzo supplies the vocabulary. It defines binding and bound occurrences of a variable and the scope of a binding, using a function parameter as the first example. It then argues that ISL list abstractions are loops, but different from conventional ones: they build new data rather than only repeating actions, and programmers define new ones as needed. The last section shows pattern matching as a notation that replaces the predicate-and-selector clauses of a template, using the 2htdp/abstraction teachpack.

Key Points:

  • The parameter in a function header is a binding occurrence; its uses in the body are bound occurrences.
  • The scope of a binding is the region of the program where that name refers to it.
  • ISL loops such as map and build-list compute new data from a traversal.
  • Conventional languages offer a fixed set of loop forms, whereas an ISL programmer defines new abstractions.
  • Pattern matching combines a predicate test with the selection of fields in one clause.

Practice Tip: In a small function with a local, circle every binding occurrence and draw an arrow to each of its bound occurrences. It makes shadowing visible.

Common Mistake: Reusing one name for two variables in nested scopes and assuming they are the same. The innermost binding wins.

Important Questions:

  • What is the difference between a binding and a bound occurrence? A binding occurrence introduces the name, such as a parameter, while bound occurrences are the uses of that name inside its scope.
  • How do ISL loops differ from loops in conventional languages? They create new data from a traversal instead of only repeating a statement, and programmers can define their own instead of being limited to a fixed set.

Chapter 19: The Poetry of S-expressions

Part IV: Intertwined Data · Difficulty: Hard · Key topics: trees, forests, mutual recursion, S-expressions, Atom, binary search tree, function simplification

Part IV deals with data definitions that refer to each other. Chapter 19 begins with family trees, whose ancestor definition needs a second definition for the parents, then forests of trees. It introduces S-expressions, an idea credited to John McCarthy and his colleagues in 1958, as one data definition for nested lists of atoms. The design recipe becomes a rule: draw arrows between the definitions, write one template per definition, and let function calls follow the arrows. A binary search tree project and a section on simplifying a substitute function finish the chapter.

Key Points:

  • Mutually referential data definitions require templates developed together, one function per definition.
  • If definition A refers to definition B, then the template for A calls the function for B in the same place.
  • An S-expression is an atom or a list of S-expressions, which makes it a flexible representation for nested data.
  • A binary search tree stores information so that lookup can skip half of the tree at each step.
  • After a function works, you can often merge or inline auxiliary functions while keeping the tests green.

Practice Tip: Draw a family tree on paper, write its data definition, and mark the references with arrows before you write any template.

Common Mistake: Writing one template for a group of mutually referential definitions. Each data definition gets its own template and function.

Important Questions:

  • How do you design functions for intertwined data? Draw arrows from each reference to the definition it points to, write one template per definition, and make the template of A call the function for B wherever A refers to B.
  • What is an S-expression? A data definition for either an atom or a list of S-expressions, used to represent arbitrarily nested data such as programs or XML.

Chapters 20-21: Iterative Refinement; Refining Interpreters

Part IV: Intertwined Data · Difficulty: Hard · Key topics: iterative refinement, directory trees, data analysis, interpreter, BSL expressions, association list, variables, function definitions

Chapter 20 teaches iterative refinement as scientists use it: build a model, test it against the real world, and improve it. The example is a computer’s file system. You start with directories that only list names, refine the data definition to include file sizes and then more attributes, and refine the functions to match, using the directory-reading teachpack on small directory trees first. Chapter 21 applies the same method to an interpreter: it represents BSL expressions as data, then adds variables with an association list, function definitions, and finally constant and function definitions together, so you write a small version of DrRacket’s interactions area.

Key Points:

  • Refine a model in small steps and decide at each step which attributes to keep and which to ignore.
  • The directory example moves from Dir.v1 to Dir.v2 and Dir.v3 as more attributes are added.
  • Use the teachpack’s own directory structures; defining your own structure type with the same name is an error.
  • An expression is represented as data: numbers stand for themselves, and additions and multiplications are structures.
  • An association list maps variable names to values for the interpreter.
  • Evaluating a function call substitutes the argument values into the function’s body representation.

Practice Tip: Represent the BSL expression (+ 1 (* 2 3)) as nested data and evaluate it by hand with your own template before you write the code.

Common Mistake: Trying to handle every file attribute from the first version. Start with the smallest model that answers the question, then refine.

Important Questions:

  • What is iterative refinement? A process of building a simplified model, testing it against the real world, and adding detail in stages, as in the three directory data definitions.
  • How does the book evaluate expressions with variables? It replaces each variable with the value it is bound to in an association list, then evaluates the resulting expression.

Chapters 22-23: The Commerce of XML; Simultaneous Processing

Part IV: Intertwined Data · Difficulty: Hard · Key topics: XML, Xexpr, domain-specific languages, reading XML, two inputs, three cases, function simplification, database

Chapter 22 treats XML as S-expressions. It defines a data representation for XML elements, renders XML enumerations as pictures, turns an XML description of finite state machines into a running program as an example of a domain-specific language, and shows how reading XML from files or web pages brings in the outside world. Chapter 23 is about functions of two complex inputs. It separates three cases: one argument treated as atomic, both arguments processed in lockstep, and every combination handled separately. It simplifies the resulting functions and ends with a database project built on schemas and integrity checks. Chapter 24 summarises the part.

Key Points:

  • XML data can be represented as S-expressions, which is why quasiquote is useful for writing it.
  • A domain-specific language lets a configuration file describe a program’s data without editing its code.
  • Reading files or web pages changes the computational model, since the program no longer depends only on its arguments.
  • With two complex inputs, decide first whether one is atomic, both move together, or all combinations matter.
  • For the third case, draw a two-dimensional table of data classes and fill each cell with a cond clause.
  • A database is a table plus a schema, and integrity checks verify that rows match the schema.

Practice Tip: Write list-pick and start with the table of cases for the list and the number. You will see which cells can be merged.

Common Mistake: Assuming two list arguments always need the lockstep template. If one list is never decomposed, treat it as atomic.

Important Questions:

  • What are the three cases for functions with two complex inputs? One argument is treated as atomic; both are processed in parallel; or all combinations of the two data definitions are handled separately.
  • What is a domain-specific language? A small language for describing one kind of problem, such as the configuration of a finite state machine, represented as data that the main program interprets.

Intermezzo 4: The Nature of Numbers

Part IV: Intertwined Data · Difficulty: Medium · Key topics: fixed-size numbers, inexact numbers, overflow, underflow, exact and inexact arithmetic

Programming languages sit between mathematics and hardware, and this intermezzo explains what that does to numbers. Hardware stores numbers in fixed-size chunks, so arithmetic must approximate. The book builds a toy representation called Inex with a mantissa and an exponent and uses it to show what happens when an operation produces a number too large to represent (overflow) or too small (underflow). It ends by describing how the teaching languages treat exact and inexact numbers, including their integers, so unexpected answers have an explanation.

Key Points:

  • Fixed-size representations can hold only a finite set of numbers, so results are approximated.
  • Inexact numbers print with a #i prefix in the teaching languages.
  • Overflow means a result is too large to represent; some systems signal an error and others use infinity.
  • Underflow means a result is too small; some systems signal an error and others use 0, which drops the whole value so the error is no longer within a predictable percentage.
  • The teaching languages support both exact and inexact numbers, and exact integers are not limited to a fixed size.

Practice Tip: Evaluate (sqrt 2) and then (* (sqrt 2) (sqrt 2)) in DrRacket and compare the result with 2. The small error is the point of the intermezzo.

Common Mistake: Using exact equality on inexact results. Compare with a tolerance, or avoid comparing computed decimals directly.

Important Questions:

  • What is overflow? It happens when a result is too large for the chosen representation; the language may signal an error or return a symbolic infinity.
  • Why does underflow differ from ordinary rounding? Rounding keeps the answer within a predictable percentage, but replacing an underflowed result by 0 drops the whole value.

Chapters 25-26: Non-standard Recursion; Designing Algorithms

Part V: Generative Recursion · Difficulty: Hard · Key topics: generative recursion, bundle, quick sort, trivial case, termination, structural versus generative recursion

Part V introduces the eureka step. Chapter 25 shows two functions whose recursion does not follow the shape of their input: bundle, which splits a string into chunks as part of a DrRacket sharing service, and a quick sort that partitions numbers around the first item and sorts both parts. Chapter 26 adapts the design recipe. You still define data and examples, but the template asks whether the problem is trivial and how to generate a new, simpler problem. The chapter explains termination, which structural recursion guarantees and generative recursion does not, compares the two kinds, and discusses how to choose. Chapter 30 summarises the part.

Key Points:

  • Generative recursion calls the function on newly generated data, not on a piece of the input; most computer scientists call these functions algorithms.
  • The coding step adds four questions: what is trivial, what is its answer, how to generate a new problem, and how to combine answers.
  • Structurally recursive functions always terminate because the input shrinks; generative ones may not.
  • Functions that may fail to terminate need a comment warning future readers about bad inputs.
  • Quick sort and insertion sort are observably equivalent, so choosing between them is about performance.

Practice Tip: Test your quick sort on a list with repeated numbers. If you partition with only “less than” and “greater than”, duplicates will vanish.

Common Mistake: Writing a generative call whose new problem is not smaller than the old one. The program will loop, so argue why each generated problem is closer to trivial.

Important Questions:

  • How does generative recursion differ from structural recursion? Structural recursion follows the data definition and recurs on a piece of the input, whereas generative recursion creates new data from the input through a clever idea and recurs on that.
  • Why can a generative function fail to terminate? The generated problem may not be simpler than the original, so the recursion never reaches a trivial case.

Chapters 27-28: Variations on the Theme; Mathematical Examples

Part V: Generative Recursion · Difficulty: Hard · Key topics: fractals, Sierpinski triangle, binary search, parsing, Newton’s method, numeric integration, Gaussian elimination

These two chapters supply examples of algorithmic ideas. Chapter 27 starts with fractals as a first taste of recursive drawing, then binary search for the root of a numeric function, using a rocket-hitting-its-target problem, and a glimpse of parsing that turns a file’s characters into lines. Chapter 28 collects mathematical problems that rely on generative recursion: Newton’s method as another way to find roots, numeric integration to estimate distance travelled by a car or rocket, and a project that solves systems of equations by Gaussian elimination, with a data representation for equations and solutions.

Key Points:

  • An algorithm starts from an informal idea for making the problem smaller or easier.
  • Binary search narrows an interval that contains a root by looking at the midpoint at each step.
  • Parsing converts a flat sequence of 1Strings into structured data such as a list of lines.
  • Numeric integration approximates the area under a function by summing small pieces.
  • Gaussian elimination reduces a system of equations step by step until the solution is visible.

Practice Tip: Implement the interval-halving search for a simple function such as a straight line and count how many halvings it needs. Then try a smaller tolerance.

Common Mistake: Choosing a stopping tolerance that is too small for inexact numbers. The interval may never shrink enough, so the recursion keeps going.

Important Questions:

  • How does binary search find a root? It keeps an interval whose ends give function values of opposite sign, checks the midpoint, and recurs on the half that still contains the sign change.
  • What problem does parsing solve? It turns a sequence of characters into structured data, such as turning a list of 1Strings into a list of lines.

Chapter 29: Algorithms that Backtrack

Part V: Generative Recursion · Difficulty: Hard · Key topics: graphs, nodes, traversal, cycles, backtracking, n queens puzzle

Some problems cannot be solved by a straight line of steps, and this chapter presents two that rely on backtracking. The first section defines graphs, with nodes and directed connections between them, and designs an algorithm that finds a path between two nodes by trying neighbours and going back when a choice fails. The second section is a project on the n queens puzzle on an n by n chess board, using backtracking to find placements where no two queens attack each other. Chapter 30 follows with the summary of Part V.

Key Points:

  • A graph is a collection of nodes with connections; the data definition needs a way to find a node’s neighbours.
  • Backtracking tries one choice, and if it fails, returns to the last decision to try another.
  • A queen attacks along rows, columns and diagonals, so a placement must avoid all three.
  • Generative recursion on a graph needs a guard against cycles, or the algorithm may loop forever.
  • The Part V summary asks you to document inputs for which an algorithm may not terminate.

Practice Tip: Draw a graph with a cycle on paper and trace the path search by hand. You will find exactly where the visited-node knowledge is missing.

Common Mistake: Ignoring cycles in a graph traversal. The simple version loops forever, which is one reason Part VI exists.

Important Questions:

  • What is backtracking? An algorithm design in which you follow one option and, when it leads to a dead end, return to the earlier decision and try the next option.
  • What is the n queens puzzle? Place n queens on an n by n board so that no two attack each other along a row, column or diagonal.

Intermezzo 5: The Cost of Computation

Part V: Generative Recursion · Difficulty: Medium · Key topics: running time, abstract time, order of growth, big-O, predicates and selectors, cost of length

Timing a program shows how long it takes for particular inputs and nothing else, so this intermezzo develops an abstract measure. It counts recursive steps as a function of input size, using how-many on lists as the first example. It then defines what “on the order of” means, so two programs that compute the same answers can be compared by how their cost grows, with the structural gcd and gcd-generative from Chapter 26 as the case in point. The last section asks why programs use predicates and selectors, since a design that calls length can silently make an O(n) search cost O(n squared).

Key Points:

  • Abstract running time counts recursive steps as a function of input size, ignoring machine speed.
  • A program is on the order of n if its steps grow in proportion to the input size n.
  • Two programs that give the same answers can differ greatly in cost.
  • Calling length inside a recursive function adds a hidden traversal each time.
  • The cost model assumes that predicates and selectors take a fixed amount of time.

Practice Tip: Count the recursive calls of a list function on lists of 10, 20 and 40 items and check whether the count doubles when the input doubles.

Common Mistake: Measuring a program once on a small input and deciding which of two programs is faster. Compare how cost grows with input size.

Important Questions:

  • What does “on the order of n” mean? The number of steps grows at most in proportion to n, up to a constant factor, once n is large enough.
  • Why can using length in a recursive search make it slower? Each call traverses the whole list to count it, so a search of n items can take on the order of n squared steps.

Chapters 31-32: The Loss of Knowledge; Designing Accumulator-Style Functions

Part VI: Accumulators · Difficulty: Hard · Key topics: loss of knowledge, accumulator, accumulator statement, invariant, relative to absolute distances, graph with cycles

Part VI asks what a function forgets when it recurs. Chapter 31 gives two examples. Converting relative distances between road points into absolute distances is a plain structural exercise, yet each recursive call forgets the distance already travelled. Checking whether two nodes are connected in a graph where each node has one outgoing connection shows a case where the function cannot work without remembering nodes it has already seen. Chapter 32 gives the recipe: recognise the need, add an accumulator parameter with an accumulator statement, derive its initial value and updates, and practise on the mouse-enabled graphical editor.

Key Points:

  • Structural and generative functions both lose context when they recur on a piece of the input.
  • An accumulator is an extra parameter that gathers knowledge during the traversal.
  • The accumulator statement says what the accumulator means in terms of the original argument and the current one.
  • From the statement you derive the initial value, how to update it on each call, and how to use it.
  • Reversing a list with a helper that appends to the end suggests an accumulator: the original invert traverses its own result.

Practice Tip: Write the relative-to-absolute distance function twice, once structurally and once with an accumulator. Compare the code and the stepper traces.

Common Mistake: Adding an accumulator without writing its accumulator statement. If you cannot explain what it holds, you cannot show the function is correct.

Important Questions:

  • What is an accumulator? An additional parameter that carries knowledge gathered so far, such as the distance already travelled or the nodes already visited.
  • When should you consider an accumulator? When a recursive function traverses the result of its own recursion with another recursive helper, or when it cannot work without remembering what it has seen.

Chapter 33: More Uses of Accumulation

Part VI: Accumulators · Difficulty: Hard · Key topics: accumulators and trees, compilation, declared variables, data representations with accumulators, accumulators as results, Sierpinski triangle

The last full chapter shows three more settings for accumulation. In the first, a piece of DrRacket’s compiler checks that every variable in an ISL+ program is declared by define, define-struct or lambda, and an accumulator records the names in scope. The second puts an accumulator inside a data representation so that the size of a container does not have to be computed by traversal. The third uses an accumulator as the result of a function, illustrated by adding a Sierpinski triangle to an image. Chapter 34 summarises the three steps of accumulator design.

Key Points:

  • When a function processes a tree, the accumulator can record the context of the current node, such as the names in scope.
  • The compiler example checks that each variable is declared before use.
  • Placing an accumulator in a data structure avoids repeated traversal, for example storing the size with a container.
  • An accumulator can also be the result, as when the picture is passed along and extended.
  • Summary steps: recognise the need, write the accumulator statement, derive initial value, update and use.

Practice Tip: Enter x, (lambda (y) x) and (x 5) as complete ISL+ programs and read the error each time. Then design the check for undeclared variables.

Common Mistake: Forgetting that a lambda parameter is in scope only inside its body, so the accumulator must grow when entering it and not leak out.

Important Questions:

  • How can an accumulator speed up size computation? Store the size inside the data representation and update it when items are added, so asking for the size no longer needs a traversal.
  • What does an accumulator do in the Sierpinski example? It carries the image being built, so each recursive step adds its smaller triangles to the picture produced so far.

Epilogue: Moving On

Difficulty: Easy · Key topics: computing as generalized calculating, program design as communication, next steps for developers and for everyone else

The epilogue stops to look back and ahead. It describes computing as a generalization of the calculating you learned in school, moving from counting to variables and functions. It argues that the design structure of a program is a means of communication among programmers across time, since projects with thousands of functions outlive their authors. It then points developers and computer scientists to more programming and more computing in full-fledged languages, and tells accountants, journalists, surgeons and everyone else what the course gave them: a sense of what separates a garage programmer from a serious developer.

Key Points:

  • Computing generalizes the calculating learned in elementary school.
  • Program design is communication among programmers across time.
  • The next step for computer scientists is to apply the design process in a full-fledged language.
  • Some mainstream languages resemble the teaching languages and others do not, so expect an adjustment.
  • Non-programmers still gain the ability to talk to developers and judge their work.

Practice Tip: Choose a program you wrote earlier in the course and write the signature, purpose statement and data definition for each function in plain comments. Hand it to a friend and see if they can read it.

Common Mistake: Treating the end of the book as the end of learning. The epilogue expects you to learn more computing and more languages next.

Important Questions:

  • Why does the epilogue call program design a form of communication? Large projects pass through many programmers over time, so signatures, purpose statements and data definitions are how one person explains the program to the next.
  • What should a computer science student do after this book? Learn how the design process applies in a full-fledged programming language, and study more computing topics.

How to Study This Book

The book is a workbook, not a reading book. It numbers 528 exercises from 1 to 528, spread across the chapters, and the authors expect you to run every example in DrRacket, the free programming environment built for it. Plan to type as you read. Prologue and Chapters 1 to 6 reward patience and punish skimming: the design recipe from Chapter 3 is used in every later chapter, so do the finger exercises in Sections 3.2 and 9.1 before moving on.

The language level changes as you go. Part I uses Beginning Student Language, Chapter 11 moves you to the version with list abbreviations, Part III switches to Intermediate Student Language, and lambda arrives with its extended version. Set the level from the Language menu at the start of each part, because many errors in later chapters are simply the wrong level.

This page groups chapters into 24 blocks so the list stays readable: 34 numbered chapters plus 5 intermezzos and the prologue and epilogue are too many for one block each. Blocks never cross a part boundary, and the six short summary chapters (7, 13, 18, 24, 30 and 34) are folded into the block before them. The authors suggest several paths through the book in the preface, including one that stops after the first two parts, so you can read in layers.

For a first-semester programming fundamentals course, Parts I and II (Chapters 1 to 13) are the core: data definitions, the design recipe, structures, lists and recursion. Add Part III (Chapters 14 to 17) when your course reaches higher-order functions, and read the intermezzos when the chapter before them points to them. Intermezzo 1 pairs well with Chapter 6, and Intermezzo 5 prepares you for complexity analysis in a data structures course.

Parts IV, V and VI are algorithm and data-structure material in disguise. Chapter 19 on trees and S-expressions, Chapters 25 to 29 on generative recursion and backtracking, and Chapters 31 to 33 on accumulators suit a second course or a motivated reader. Part V depends on Chapters 9 to 11, and Part VI relies on Part V and Intermezzo 5, so do not jump straight to accumulators.

Be clear about what the book does not cover. It does not teach C++, Java or Python, and it leaves out pointers, objects, loops with assignment, and concurrency. The preface says imperative design belongs to a later volume, How to Design Components. Use it for the habit of designing before coding, then practise that habit in your course language. Chapter 12.2 describes iTunes, so expect the export steps to differ on a modern Mac.


Used In These Programs

This book is used for the Programming Fundamentals course in: BS Computer Science. Browse all Programming Fundamentals books, Programming books or all Computer Science books.

Who Should Read This

This book is written for first-year BSCS students and for anyone starting programming who wants to learn to design before they code. It assumes only school-level mathematics, and it suits a Programming Fundamentals or Introduction to Computing course, especially if you want the design habits behind whatever language your course uses. It is a poor fit if you need a C++ syllabus book for an exam, or a quick language reference, and it is not an entry-test guide. The teaching languages run in DrRacket, so you will not practise the syntax your lab uses; to see the same ideas in mainstream languages, pair it with Think Python or Think Java, and read Structure and Interpretation of Computer Programs afterwards for a more demanding take on the same Scheme-family tradition.


Applicable Universities

This book is useful for students at Pakistani universities offering BS Computer Science, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.

Official Copy of How to Design Programs

This book is free from its official site. The authors publish no PDF, so the legitimate free way to read it is the complete online edition. Click the button below to open htdp.org, where the cover links to the current version of the book. A printed edition is sold by MIT Press.

→ Visit Official Page

FAQs

Is How to Design Programs free?

Yes. The authors publish the full second edition free at htdp.org. The page states that the material is copyrighted by MIT Press and provided under the Creative Commons CC BY-NC-ND licence, and its licence links point to version 2.0. That licence lets you read and share the book with credit for non-commercial use, but not change it.

Is there a PDF of How to Design Programs?

The official site does not offer a PDF. The free version is the online HTML book, and a printed copy can be bought from MIT Press. This page links only to the official site and does not host any file.

Which edition and version is this?

It is the Second Edition. The online version at the time of writing is 9.2.0.3, released on 28 May 2026, and the authors take error reports at authors @ htdp.org. The first edition is still hosted on the same site, but the second edition is the current one.

How many chapters and exercises does it have?

There are 34 numbered chapters in six parts, a prologue, five intermezzos and an epilogue. Six of the chapters are short part summaries. The exercises are numbered from 1 to 528 across the book, including finger exercises and larger projects.

Is it good for complete beginners?

Yes in the sense that it assumes no programming background and only school-level mathematics, starting from arithmetic in the prologue. It is demanding in another sense, because it expects you to follow the design recipe step by step and to type and test every example in DrRacket.

Does it teach C++, Python or Java?

No. The book uses the teaching languages of the Racket family, from Beginning Student Language up to Intermediate Student Language with lambda, inside the DrRacket editor. Those languages are small on purpose, so they have no C++ syntax, pointers or objects. Use the book for the design habits and practise the same habits in your course language.

Related Books

How to Design Programs is a slow, careful way to learn what a well-designed program looks like before you worry about any one language. It will not replace your C++ or Java textbook, but it gives you a recipe for turning a problem into data definitions, examples and tests. Browse more Computer Science books for the rest of your semester.

How to Design Programs, Second Edition by Matthias Felleisen, Robert Bruce Findler, Matthew Flatt and Shriram Krishnamurthi. Copyright 2014 MIT Press; print edition by MIT Press. The online edition is provided under the Creative Commons Attribution-NonCommercial-NoDerivatives 2.0 licence (CC BY-NC-ND 2.0). Official source: https://htdp.org/. This page links to the official site and does not host or copy the book.

Leave a Comment