This page presents the mini-projects of Programming Paradigms: the suggested topics of the project (on which the oral exam will be held), and the common modalities and deadlines for projects, mandatory reports, and the expected amount of work. Each topic revolves around a research question and a program to build that will apply design decisions studied in the course; its core can be adjusted by a group, on the terms below. The topics are listed in a table, each presented below in more detail. A topic from this list is option (b) of the exam format; an extension of the semester project, option (a), and a topic of the group’s own, option (c), remain possible on the terms of that page.
A longer description of a topic, with a specification and a worked small version, is written on request for a group that is considering it; a message to the lecturer is enough.
A mini-project is sized as the preparation for the oral exam, a share of the self-study of the course, and two to four lab sessions; at least two lab sessions are dedicated to help with the projects.
On AI: the report declares its use, ideally with three to five examples, each giving the request, the generated output, and the change the group made to it. At the oral every student explains any part of the work, so generated code that the group cannot explain is a risk.
Several groups may choose the same topic. The list may grow until the deadline for own proposals; a topic added later is announced on Moodle.
A click on a column heading with arrows orders the table, and the descriptions below follow the same order.
The parts of the course: 1, data and control (sessions 2 to 5); 2, coordination and communication (sessions 6 to 9); 3, types and abstraction (sessions 10 to 13).
1 The insulin game
Part 1 · Sessions 4 and 5, lab 5
The question. Where do higher-order functions, closures and state appear when a cell makes a protein, and what does a traversal need in order to stop? Molecular biology lends itself to this kind of model: the cell’s machinery reads one sequence and writes another (DNA into RNA, RNA into protein), so each stage is a function over a list, the stages compose into a pipeline, and the higher-order functions of the course (map, folds, composition) describe them directly. The path from the insulin gene to glucose entering a muscle cell has ten steps, and each is a list operation: transcription is a map; translation reads codons until the stop codon, which a plain fold cannot do, since a fold visits the whole list; the trigger is a closure over the cell’s state. The decision is control: who drives the loop, and what a fold cannot do.
The core. A programming game in which each step of the pathway is a level: the player first writes a list tool, then uses it on the biology. Another pathway may replace insulin’s, with four levels of the same kinds.
- The biology of the four steps that the levels play, as a tested library: transcription, translation to the 110 residues of human preproinsulin (UniProt’s entry P01308, with the standard genetic code), the stop codon, and the trigger.
- Four levels as data (task, stub, tests as closures, hints): transcription with
map, translation, the stop codon, where the traversal must stop, and the trigger, a closure.
- An engine that is a fold over the levels, and a command-line game that runs a player’s file against a level’s tests and unlocks the next level.
- Evidence: a test that translation stops at the stop codon, and the report’s account of whether the chosen traversal reads any codon after it.
Directions. The six remaining steps of the pathway, with their biology, as levels; a sandbox that hides List.map and List.fold_left until the level that defines them; the game in the browser, with OCaml compiled to JavaScript; translation as an external iterator that can be paused; compiler error messages rewritten for beginners; undo for the player as persistent state; a second pathway on the same engine.
To start. PDB-101, “Molecule of the Month: Insulin”; X. Leroy, Control structures in programming languages, chapter 4, “Control inversion”; Real World OCaml, “Lists and Patterns”.
↑ Back to the table
2 Mini-git: a repository as a persistent map
Part 1 · Session 2, lab 2
The question. What does a data structure buy when no operation ever overwrites, and what does it cost? Git keeps every version of a project because stored data is never overwritten: a commit adds new immutable objects and reuses the unchanged ones, and a branch is only a name for a commit. The project builds that design on a persistent map. The decision is state: ephemeral or persistent, with sharing between versions as the consequence of never mutating.
The core. A small repository on a persistent map.
- A balanced persistent map (AVL or red-black) from paths to contents, behind an abstract signature, with its laws as tests on random sequences of operations.
- A repository on the map: a commit is a new root, a branch is a name for a root, checkout selects a branch, and a log lists the commits.
- A diff that stops at the subtrees two versions share (the same node in memory, not merely equal).
- Evidence: on a generated history of a thousand commits, the memory held by all the versions against one full copy per commit, and the number of nodes the diff visits, in one table that the report explains.
Directions. A real history replayed from git; content addressing by hashes; a three-way merge; a second representation (a hash array mapped trie) behind the same signature; readers that take a snapshot without a lock while one thread commits.
To start. Pro Git, chapter 10, “Git Internals”; C. Okasaki, Purely Functional Data Structures (1998), chapter 2, on persistence and path copying.
↑ Back to the table
3 Planar point location: slabs that share
Part 1 · Session 2 (the sweep with a persistent tree)
The question. What does keeping earlier versions of a structure cost when an algorithm queries every intermediate state? Given segments in the plane that do not cross, which two segments lie just below and just above a query point? Sorting the segments within vertical slabs answers a query in O(log n) but stores O(n²); a sweep that keeps the segments in a persistent balanced set, one version per slab, shares nodes between consecutive slabs. This is the problem that gave persistent data structures their name (Sarnak and Tarjan, 1986).
The core. The slabs, then the sweep with a persistent set.
- The brute force as the oracle, and the slabs with sorted arrays.
- The sweep: each segment added at its left endpoint and removed at its right one, in a persistent balanced set ordered by height at the current position of the sweep, and the version after each event kept. A persistent set from the language’s library is allowed (OCaml’s
Set is one); writing the tree is a direction. Where the set fixes its comparison when it is created, as OCaml’s does, the comparison reads the position of the sweep from a reference that the sweep advances: between two events the order of the segments present does not change, which is why this is sound.
- Queries by two binary searches, checked against the oracle on generated inputs whose assumptions (no vertical segment, distinct abscissae) the report states.
- Evidence: memory and query time of the slabs and of the sweep as n grows, in one table, and the report’s account of why the order of the segments stays valid between two events.
Directions. The persistent AVL tree written by the group, with its nodes counted; fat nodes, an imperative tree made persistent, which bring the space to O(n) and a query to O(log² n); bounded histories, which restore O(log n) queries; a real map with the assumptions lifted; a picture of the shared nodes.
To start. N. Sarnak and R. E. Tarjan, “Planar point location using persistent search trees”, Communications of the ACM, 1986; E. Demaine, MIT 6.851 Advanced Data Structures, lecture 1, “Persistent data structures” (video and notes).
↑ Back to the table
4 Rope, piece table, gap buffer
Part 1 · Sessions 2 and 5, lab 5
The question. Lab 5’s editor stands on a persistent rope. Other editors use a piece table (VS Code keeps one in a balanced tree) or a gap buffer (Emacs). What does each representation make cheap, what does it make expensive, and which keeps old versions at no cost? The decision is state and data abstraction: three representations behind one contract.
The core. Two representations beside the lab’s rope, behind one contract; another representation, such as an array of lines, may replace one of the two.
- A piece table and a gap buffer behind one contract with the rope: an editor’s operations on the current document (insert, delete, the character at a position, a traversal of a range), with undo kept as a history beside it. The rope keeps its old versions at no cost; the piece table and the gap buffer record what undo needs, and the report says how.
- One test suite run against the three representations.
- Evidence: the cost of typing in one place, typing in many places, and undoing, measured on a generated file of several megabytes, with the workload and the undo policy stated.
Directions. The lab’s editor run on each representation; files of a hundred megabytes; a balanced rope, and when to rebalance; several cursors at once; the piece table in a language without a garbage collector.
To start. VS Code blog, “Text Buffer Reimplementation”, 2018; C. Crowley, “Data Structures for Text Sequences”, 1998; H.-J. Boehm, R. Atkinson and M. Plass, “Ropes: an alternative to strings”, Software: Practice and Experience, 1995.
↑ Back to the table
5 Regular expressions with continuations
Part 1 · Sessions 4 and 5, lab 5 (part C)
The question. Lab 5’s matcher handles ? and * with two continuations: succ for what follows a match, and fail for where to go back. How far does that design reach, and what does it cost against a matcher compiled to an automaton? The decision is control: backtracking as continuations, against a state machine.
The core. Two matchers for one small pattern language.
- Patterns as values of a datatype: literals, any character, concatenation, alternation,
* and +.
- The continuation matcher of lab 5 extended to these patterns, answering whether the whole text matches.
- The same patterns compiled to a nondeterministic automaton (Thompson’s construction) and simulated without backtracking.
- Evidence: the two matchers agree on generated patterns and texts; on the pattern
a?nan against the text an, the work of the backtracking matcher grows exponentially with n and that of the automaton polynomially, measured.
Directions. A parser for the usual syntax; character classes and anchors; all the matches in a text; capture groups in both designs; backreferences, which can describe languages that no finite automaton recognises; a deterministic automaton built lazily while matching.
To start. R. Cox, “Regular Expression Matching Can Be Simple And Fast”, 2007; R. Harper, “Proof-directed debugging”, Journal of Functional Programming, 1999 (the matcher with continuations).
↑ Back to the table
6 Persistent union-find generates the mazes
Part 1 · Session 2, lab 2
The question. Union-find is the classic imperative structure: path compression rewrites the parent links along each search, so the usual implementation mutates even when it only answers a question. Can it be made persistent without losing its speed? The mazes that lab 2 solves can be generated by a union-find over the cells (Kruskal’s algorithm). The decision is state: persistence where the efficient algorithm mutates.
The core. Two union-finds, one maze generator.
- The imperative union-find, with union by rank and path compression.
- A persistent union-find on a persistent map, behind the same signature.
- A maze generator by Kruskal’s algorithm on either, whose mazes lab 2’s solver solves.
- Evidence: the cost of the two as the grid grows, and a query on an old version repeated after later unions, with the report’s account of what path compression does to each.
Directions. The persistent union-find of Conchon and Filliâtre (2007), with the mutation hidden behind a persistent interface; a generator that backtracks to old versions, for example to obtain a long path; mazes on other grids; the generator run in parallel.
To start. R. Sedgewick and K. Wayne, Algorithms, section 1.5, “Union-Find”; J. Buck, “Maze Generation: Kruskal’s Algorithm”; S. Conchon and J.-C. Filliâtre, “A persistent union-find data structure”, ML Workshop, 2007.
↑ Back to the table
7 Exact cover, three ways: backtracking
Part 1 · Sessions 2, 4 and 5, lab 5 (part C)
The question. Sudoku and the tiling of a board by polyominoes are exact cover problems: choose rows of a 0–1 matrix so that every column is covered exactly once (the N-queens problem too, with columns that may stay uncovered). The search for a cover is backtracking: a choice is made, its consequences are applied, and at a dead end they are undone. How is the undo done best: by mutating the matrix and restoring it, by keeping the previous version, or by leaving it to the structure of the search? The decision is state and control: undo by mutation, by persistence, or by continuations.
The core. One problem, two solvers, the same solutions.
- Exact cover as a datatype, and Sudoku encoded in it: 729 rows (a value in a cell) and 324 columns (each cell filled, and each value once in each row, column and box).
- Knuth’s Algorithm X on persistent sets: each choice gives a new version of the matrix, and backtracking returns to the previous version at no cost.
- Algorithm X with dancing links: a doubly linked matrix that a choice mutates by unlinking columns and rows, and that backtracking restores by relinking them in reverse order.
- Evidence: both solvers find the same solutions on a set of puzzles, and the same number of solutions on a puzzle that has several; the time and memory of each are measured, and the report explains why relinking in reverse order restores the matrix exactly.
Directions. The solutions as a lazy sequence, so that a client takes the first or counts them all (session 5); the search written with success and failure continuations, as lab 5’s matcher (session 4); the N-queens problem with columns that may stay uncovered; the choice of the column with the fewest rows, measured against the first column; a search split in parallel over the first choice.
To start. D. E. Knuth, “Dancing links”, 2000; P. Norvig, “Solving Every Sudoku Puzzle”.
↑ Back to the table
8 A scheduler on a hand-made await
Part 2 · Session 6, lab 6
The question. When a program waits without threads, what decides which continuation runs next, and what does the programmer owe? The quest of lab 6 builds a loop that runs queued continuations in the order they arrive. A user interface needs its clicks before its network replies, a server needs a request abandoned after a second, and a test needs a run that is the same every time. The decision is control and concurrency on one thread.
The core. Lab 6’s loop, given priorities and a clock.
- The loop of lab 6’s quest extended with priorities: a ready continuation of higher priority runs first.
- A virtual clock: timers fire in the order of their deadlines, so that a test of the loop gives the same result every time.
timeout(p, ms) on that clock: it settles with the value of p, or rejects when ms have passed first.
- Evidence: three traces of the order of events, each explained from the loop’s rules, one of them showing a priority that changes the order.
Directions. Cancellation that reaches a generator suspended at a yield and runs its finally; structured concurrency, a scope that cancels its children when one fails; the same traces on Node, in the browser and on Python’s asyncio, each explained from that runtime’s rules; a lock held across an await; the loop in OCaml 5 with effect handlers; the cost of a thousand waits.
To start. J. Archibald, “Tasks, microtasks, queues and schedules”; N. J. Smith, “Notes on structured concurrency, or: Go statement considered harmful”.
↑ Back to the table
9 Lock-free: one queue, three disciplines
Part 2 · Session 7, lab 7
The question. What does an operation on a shared structure need in order to be atomic without a lock, what does the language guarantee about it (atomic operations, a memory model, garbage collection), and what is left to the programmer? A shared queue sits inside every scheduler, logger and message broker; Java’s ConcurrentLinkedQueue is based on the lock-free queue of Michael and Scott (1996).
Before starting. Session 7 introduces compare-and-swap; the algorithm and the terms linearisable, linearisation point and helping are in the paper of Michael and Scott and in chapter 10 of Herlihy and Shavit, both below.
The core. One queue under a lock and without one, checked and measured; the third discipline, two locks, is a direction.
- Two queues behind one signature, in Java or Go: under one lock (lab 7’s bounded buffer is its first version), and without a lock, head and tail advanced by compare-and-swap with the helping step.
- A checker that decides whether a history of at most eight operations is linearisable, by trying every order that the instants of call and return allow.
- A harness that measures the throughput of the two queues from one to sixteen threads.
- Evidence: the linearisation point of each operation named in the code, and a version with one check removed whose history the checker rejects.
Directions. Two locks and a dummy node, the third discipline; the queue without a garbage collector, in Rust or C, with the ABA problem and the freeing of nodes; explicit memory orderings; a bounded queue; the broken version searched by a model checker.
To start. J. Preshing, “An Introduction to Lock-Free Programming”; M. Michael and M. Scott, “Simple, fast, and practical non-blocking and blocking concurrent queue algorithms”, PODC 1996; M. Herlihy and N. Shavit, The Art of Multiprocessor Programming, chapter 10, on queues.
↑ Back to the table
10 The race, in three languages
Part 2 · Session 7, lab 7
The question. The same shared bank account under two threads in Java, Go and Rust. Java and Go compile the unsynchronised program; Go’s race detector reports the race when a run executes it; safe Rust rejects the unsynchronised shared mutation at compile time. What does each language guarantee about data races, and what does each repair cost? The decision is state and communication: shared memory, mutual exclusion, ownership.
Before starting. The course writes neither Go nor Rust before this point: chapter 16 of the Rust book and A Tour of Go cover what the core needs.
The core. One race, three languages, two repairs.
- The deposit on two threads in Java and Go, with a barrier that forces the interleaving that loses a deposit, so that the loss is reproducible; a stress run as well, counting the losses over many runs.
- The same program in Rust, with the compile error explained by the rule of ownership it breaks, and the repair with
Mutex.
- Two repairs from session 7, a lock and confinement, in Java and Go, each measured.
- Evidence: Go’s race detector run on the broken version, with what it reports, and the report’s distinction between a data race and a race condition (a check followed by an act, which a lock around each access does not prevent).
Directions. A counter on compare-and-set, and when it beats a lock; the account as an actor, and the race that remains; a deadlock between two accounts produced on purpose, and the lock order that removes it; Rust’s Mutex<T> imitated in the type system of another language.
To start. The Rust Programming Language, chapter 16, “Fearless Concurrency”; The Go Blog, “Introducing the Go Race Detector”; B. Goetz and others, Java Concurrency in Practice, chapter 2, on thread safety.
↑ Back to the table
11 Channels on shared memory
Part 2 · Sessions 7 and 8, lab 7
The question. Go’s channels are values of the language, implemented by its runtime from a lock, a ring buffer and queues of waiting senders and receivers. What does it take to build them in a language that has only threads, locks and condition variables, and where does the result differ from Go’s? The decision is communication: message passing as a discipline over shared memory.
Before starting. Session 8 introduces channels on 4 November; A Tour of Go is enough to start before it.
The core. Go’s channels, rebuilt in Java or OCaml 5.
- A buffered channel of capacity n, starting from lab 7’s bounded buffer.
- The unbuffered channel, where sender and receiver wait for each other (a rendezvous).
close, with Go’s rules: a receive on a closed channel returns the values still buffered, then a zero value at once; a send on it is an error; closing it twice is an error.
- A non-blocking
select over several channels: the first ready case, or else the default branch.
- Evidence: tests of a drain after
close, a send after close, a blocked rendezvous, and a select with no, one and several ready cases, compared with small Go programs on values and blocking only, since Go chooses among ready cases at random.
Directions. A blocking select, which must wait on several channels at once without missing a wake-up; a fair select; the happens-before edges that Go’s memory model gives channels; the deadlock that Go reports as “all goroutines are asleep”, detected; the same channels on one OCaml domain with effect handlers.
To start. A Tour of Go, “Concurrency”; “The Go Memory Model”; Kavya Joshi, “Understanding Channels”, GopherCon 2017 (a talk on runtime/chan.go).
↑ Back to the table
12 Actors on threads: a mailbox each
Part 2 · Sessions 7 and 8
The question. An Erlang actor has one mailbox, selective receive, and no shared state. What does it take to build that on threads, and which race condition remains once every variable is private to an actor? No data race is possible, yet an invariant can still break between two messages.
Before starting. Session 8 introduces actors on 4 November; the chapter of “Learn You Some Erlang” below is enough to start before it.
The core. An actor runtime on threads, in Java or OCaml 5, and the race it leaves.
- An actor as a thread with a mailbox, with
spawn, send and receive.
- Selective receive:
receive takes the first message that matches a pattern and leaves the others in the mailbox, in order.
- The bank account as an actor, and a transfer written as two messages (read the balance, then write it), which loses an update under a test that orders the messages.
- Evidence: the same test with the transfer as one message, handled in one turn of the actor, and the report’s statement of the invariant (the total amount of money) that the repair keeps.
Directions. The same program in Erlang, Elixir or Akka, side by side; a link between two actors, and what the failure of one does to the other (session 9); bounded mailboxes and backpressure; the dining philosophers as five actors and a waiter.
To start. F. Hébert, “Learn You Some Erlang for Great Good!”, the chapter “The Hitchhiker’s Guide to Concurrency”; J. Armstrong, “Making reliable distributed systems in the presence of software errors”, PhD thesis, 2003.
↑ Back to the table
13 A scheduler that tries every interleaving
Part 2 · Sessions 6 and 8, lab 6
The question. The output of a concurrent program depends on the schedule. Can every schedule of a small program be run, up to a stated number of steps, so that a bug seen once in a thousand runs is found every time and printed with the schedule that causes it? The decision is control: non-determinism made into a schedule that a program chooses, enumerates and replays.
The core. A scheduler that explores, on one thread.
- Tasks as generators on one thread, on lab 6’s loop, switching only at a
yield: the yields are the scheduling points. The tasks share variables, a read and a write being separate steps, and a lock is a primitive that a task waits for until it is released.
- A scheduler whose choice of the next task is recorded, so that a run can be replayed.
- A depth-first search over these choices that enumerates every schedule up to a bound on the number of steps.
- Evidence: two small programs with a known bug each, a lost update and a deadlock, each bug found, its schedule printed and replayed, the number of schedules explored given, and the report’s statement of what the bound and the scheduling points leave out.
Directions. Channels on the loop, and a program that waits for a message that never comes; partial-order reduction, with the number of schedules before and after; random schedules from a seed, replayable; the same programs checked with a model checker (TLA+), compared.
To start. M. Musuvathi and others, “Finding and reproducing Heisenbugs in concurrent programs”, OSDI 2008 (the CHESS tool); W. Wilson, “Testing Distributed Systems w/ Deterministic Simulation”, Strange Loop 2014 (a talk on FoundationDB); H. Wayne, Learn TLA+.
↑ Back to the table
14 Two tabs, one document: a local-first editor
Part 2 · Sessions 8 and 9, lab 5; the core needs session 8 only, and session 9, on failure and retries, feeds the directions
The question. Two copies of a document are edited at once, offline, and later merged, with no server deciding which edit wins. Each copy sends its whole state, and the receiver merges it into its own. What must the merge satisfy so that the two copies agree once every update has arrived, whatever the order and however often each arrives? The decision is state and communication: replicated data, and a merge that is commutative (the order of messages does not matter), associative (their grouping does not matter) and idempotent (a message received twice changes nothing).
The core. Two replicas, two replicated types.
- Two replicas, each a running process, and between them a relay of about thirty lines, written by the group first, that delays, duplicates and reorders messages and delivers every one in the end; for one trace of the evidence, it can be set to drop a message for good. The language is the group’s choice: two instances of lab 5’s editor server in OCaml, each shown in its own browser tab, or two browser tabs in JavaScript alone.
- A counter: each replica counts its own increments under its own identifier; the merge takes the maximum for each replica, and the value is the sum.
- A set with removal (an observed-remove set): each addition carries a tag unique across the replicas, and a removal records the tags it has seen; the merge is the union of the additions and the union of the removals, and an element is present when one of its tags is added and not removed. An element added on one replica while the other removes it thus survives.
- Evidence: property-based tests of the three laws for each merge; a trace in which a naive set loses an addition that the observed-remove set keeps; a trace in which one update is lost for ever, and the report’s account of why the replicas then disagree.
Directions. A replicated sequence of characters behind the signature of lab 5’s rope (each character with a unique identifier and the identifier of the character it follows), so that the lab’s editor merges two people’s typing; retries that resend lost updates (session 9); a central server with operational transformation, compared on what each needs from the network; the size of the metadata per character after an editing session, measured.
To start. J. Lazaroff, “An Interactive Intro to CRDTs”; M. Shapiro, N. Preguiça, C. Baquero and M. Zawirski, “Conflict-free replicated data types”, SSS 2011; M. Kleppmann and others, “Local-first software”, 2019.
↑ Back to the table
15 A spreadsheet engine
Part 3 · Sessions 3 and 13
The question. A spreadsheet stores formulas whose references to other cells determine the order of evaluation; the user never states that order. When one cell changes, what does the engine recompute, how does it find a cycle, and what does it report? The decision is declarative programming: dataflow, the formula as a datatype, minimal recomputation.
The core. A small engine, with a text interface.
- Formulas as an algebraic datatype (numbers, references,
+, *, and SUM over a range), and a parser for that small grammar.
- The dependency graph, and a cycle reported as an error value in each cell it involves.
- Recomputation of only the cells that depend on a change, in topological order.
- Evidence: on generated sheets and random edits, one of which creates a cycle, the incremental engine agrees with an engine that recomputes every cell.
Directions. A grid in the browser; lazy against eager recomputation, measured on ten thousand cells; undo with persistent sheets; a type checker for formulas that tells numbers, text and dates apart; independent cells recomputed in parallel; LET and user-defined functions, which make the formulas a functional language.
To start. A. Mokhov, N. Mitchell and S. Peyton Jones, “Build systems à la carte”, ICFP 2018 (spreadsheets as build systems); Jane Street, “Introducing Incremental”.
↑ Back to the table
16 A type checker for lab 4’s interpreter
Part 3 · Sessions 4, 10 and 11, lab 4; the labs of sessions 10 and 11, on paper, work the typing rules and unification by hand
The question. Which terms does a checker reject before evaluation, which well-behaved terms does it still reject, and which further programs does let-polymorphism accept? Lab 4 runs any term. Once integers and booleans join the language, a term such as adding a function to a number gets stuck: the evaluator has no rule for it. The decision is types: what is checked, and when.
Before starting. The typing rules arrive in session 10 (18 November); the extended evaluator can be written before.
The core. Lab 4’s small ML, given types.
- Lab 4’s language extended with integers, booleans,
if and let, as in the lab’s extension “a small ML”.
- Type inference by unification with let-polymorphism (Hindley–Milner, Algorithm W), the rules and the algorithm being those worked on paper in the labs of sessions 10 and 11; the unification itself may be taken from a reading, the report saying which.
- Error messages that name the expression at fault.
- Evidence: one inferred polymorphic type explained step by step, and generated well-typed terms that the evaluator runs without getting stuck.
Directions. Pairs and records; variants and pattern matching, with a check that every case is covered; references, and the value restriction that keeps them sound; self-application, which runs and is still rejected, explained; a simply typed checker as a baseline; a second language checked by the same engine, such as the formulas of the spreadsheet topic.
To start. L. Cardelli, “Basic polymorphic typechecking”, Science of Computer Programming, 1987; B. C. Pierce, Types and Programming Languages (2002), chapters 9 and 22.
↑ Back to the table
17 Binary decision diagrams: a canonical form behind a signature
Part 3 · Sessions 2, 5 and 12
The question. A boolean function has many decision diagrams but only one that is reduced and ordered: the variables tested in a fixed order, no node with two equal children, and no two equal nodes. When every node is built through one constructor that returns the existing node whenever an equal one exists (hash-consing), two diagrams of the same function are the same node in memory, and the equality of two functions is one pointer comparison. What must an abstract type hide so that no client can build a diagram that breaks this, and what does the client gain from it? The decision is data abstraction: an invariant kept by a signature.
Before starting. Session 12 introduces data abstraction on 2 December; the lecture notes of Andersen below explain the diagrams from the beginning.
The core. A small library of diagrams behind an abstract type.
- An abstract type of diagrams whose only constructor goes through a table of unique nodes, so that equal nodes are shared and no node has two equal children.
- Negation, conjunction and disjunction by Bryant’s
apply, with a table of the results already computed.
- The number of assignments of the variables that satisfy a diagram.
- Evidence: two circuits for the same function, such as two adders built differently, shown equal by one pointer comparison; the size of one diagram under two orders of the variables, measured; and the report’s account of what the type prevents a client from doing.
Directions. The N-queens problem as one diagram, and its solutions counted; the reordering of variables; zero-suppressed diagrams, for sets of combinations; a table of unique nodes whose unused nodes the garbage collector can reclaim (weak references); the same library in a language without abstract types, and the invariant broken by a client on purpose.
To start. H. R. Andersen, “An Introduction to Binary Decision Diagrams”, lecture notes; R. E. Bryant, “Graph-based algorithms for Boolean function manipulation”, IEEE Transactions on Computers, 1986; J.-C. Filliâtre and S. Conchon, “Type-safe modular hash-consing”, ML Workshop 2006.
↑ Back to the table
18 A Datalog engine
Part 3 · Sessions 10 and 13, lab 2
The question. A Datalog program states facts and rules; an engine chooses how to evaluate them to answer a query. What does an engine need, how does it know it has finished, and what does it cost against a search written by hand? The decision is declarative programming: rules as data, matching, and evaluation to a fixed point.
The core. Positive Datalog, evaluated bottom-up.
- Facts and rules as a datatype: positive rules without function symbols, each variable of a rule’s head appearing in its body.
- The matching of a rule’s body against the known facts, binding its variables.
- Naive bottom-up evaluation: every rule applied to all the facts, again and again, until no new fact appears (the fixed point).
- Evidence: an ancestor query on a family tree traced through the successive sets of facts to the fixed point, and lab 2’s maze written as a
path relation, its answers compared with the lab’s solver.
Directions. Semi-naive evaluation, which joins only the new facts, and its saving measured; a parser for the usual syntax; stratified negation; top-down evaluation with memoisation, compared; indexes on the relations; the same queries in SQL with recursive common table expressions.
To start. S. Abiteboul, R. Hull and V. Vianu, Foundations of Databases, chapters 12 and 13 (free online); S. Ceri, G. Gottlob and L. Tanca, “What you always wanted to know about Datalog (and never dared to ask)”, IEEE Transactions on Knowledge and Data Engineering, 1989.
↑ Back to the table