00 — how to use these
Three files, and a way to read them
The solution is three files that drop into the lab folder over the ones with holes: melody.ml with every part done and Repeat in the type, and the lab's own main.ml and tunes.ml with the B2 and C4 checks switched on. Together they build without a warning and report 30 passed.
cp melody.ml main.ml tunes.ml ../lab3-melody/ # over the versions with holes
cd ../lab3-melody && dune build && dune exec ./main.exe
The warm-up has its own answer key, s3-warmup-solutions.pdf, and its companion file solved, warmup.ml.
They are most useful once our own version works, or once it is stuck: put the two melody.ml side by side and compare them one arm at a time. Every function is one match on melody, so a disagreement is always local to one constructor of one function — and that locality is the thesis of the session. This page walks through the arms in the lab's order and says what each one decides and why; the same commentary sits in the file.
01 — part A
Two numbers, and a third voice
A1 — count the notes
let rec count_notes m =
match m with
| Note _ -> 1
| Rest _ -> 0
| Seq (a, b) | Par (a, b) -> count_notes a + count_notes b
| Repeat (n, m) -> n * count_notes m
Seq and Par have the same shape — two children — and counting does not care which one it is, so one or-pattern covers both. The upper voice has 245 notes, the piece 467: a Par counts both sides, because both are played.
What we count is performed notes: a Repeat counts its body n times. The other choice, counting the notes as written, is defensible, but this one keeps a property that is worth having: for every melody, count_notes m equals the number of events to_events produces, since a rest produces no event and a note exactly one.
A2 — the length in beats
let rec length_in_beats m =
match m with
| Note (d, _) | Rest d -> beats d
| Seq (a, b) -> length_in_beats a +. length_in_beats b
| Par (a, b) -> Float.max (length_in_beats a) (length_in_beats b)
| Repeat (n, m) -> float_of_int n *. length_in_beats m
The same two arms as in A1, and now they differ: one after the other adds, at the same time takes the longer. This is the sentence the lab was built around — the constructor decides the operation — and it is why bach is 88 beats and not 176: its two voices run together, each 88 beats long. The result is a float because a dotted thirty-second is 3/16 of a beat and no integer names that.
A3 — three voices via two
let rec voices first rest =
match rest with
| [] -> first
| v :: more -> Par (first, voices v more)
Par takes exactly two melodies, so three voices is a Par inside a Par. The question was why the function takes the first voice separately instead of a plain list, and the answer is the empty list: voices [] would have to produce a chord with no notes, and no value of type melody represents one. The type has no empty melody (the homework's second question asks what it would cost to add one). A first element followed by a list is the lecture's non-empty list; with it, the meaningless call cannot be written at all, where a plain list would turn it into an exception at run time.
The result nests to the right, Par (v1, Par (v2, v3)). Part B checks that the grouping changes nothing about the sound; the only place it is visible is pretty, whose parentheses show it.
02 — part B
From a melody to sound
B1 — compile to timed events
let to_events tempo m =
let sec b = b *. 60. /. float_of_int tempo in
(* go t m = (the events of m when it starts at beat t, the beat at which m ends) *)
let rec go t m =
match m with
| Note (d, p) -> [ { at = sec t; hz = frequency p; secs = sec (beats d) } ], t +. beats d
| Rest d -> [], t +. beats d
| Seq (a, b) ->
let ea, t1 = go t a in (* a runs from t and ends at t1 ... *)
let eb, t2 = go t1 b in (* ... which is where b starts *)
ea @ eb, t2
| Par (a, b) ->
let ea, t1 = go t a in (* both from t ... *)
let eb, t2 = go t b in
ea @ eb, Float.max t1 t2 (* ... and the Par ends with the later one *)
| Repeat (0, _) -> [], t
| Repeat (n, m) -> go t (Seq (m, Repeat (n - 1, m)))
in
fst (go 0. m)
The inner function threads a clock. go t m returns two things: the events of m when it starts at beat t, and the beat at which m ends. The second result exists for Seq: b starts where a ended, and only the computation of a knows where that is. Par needs it only to compare: both halves start at t, and the Par ends when the later one does. Once the pair is there, each arm reads as its own definition.
The mistake we can hear
- Passing
ttobas well in theSeqarm: every note starts at beat 0 and the whole invention is one chord, 42 seconds long. That is thePararm, written where theSeqarm should be. - Forgetting the rests:
Rest d -> [], tinstead oft +. beats d. No event is right — a rest is the absence of one — but the clock must still advance, or the crab canon's third bar comes in early.
Events come out in reading order, a's before b's. The .wav writer is indifferent to the order, and so are the checks: a version that lists b first also passes. (One check was rewritten to make this true; an earlier version read the ninth event of the canon and failed the other order with a misleading message.)
B2 — add Repeat
One line in the type — | Repeat of int * melody — and the build prints the checklist: six times this pattern-matching is not exhaustive, one per function that matches on melody, each with the missing case spelled out. Section 04 shows the output. Nothing had to be searched for; the compiler knows every column of the table.
The arm above defines Repeat by rewriting it into Seq: n times m is m, then n − 1 times m; zero times is nothing, ending where it began. That makes the B2 check — Repeat (2, voice1) sounds exactly like voice1 ++ voice1 — true by construction rather than by coincidence: the two produce the same events because one is rewritten into the other. A counting loop that runs go n times and threads the clock is equally correct.
03 — part C
Operations on melodies
C1 — transpose by octaves
let rec transpose_octave k m =
match m with
| Note (d, p) -> Note (d, { p with octave = p.octave + k })
| Rest _ -> m
| Seq (a, b) -> Seq (transpose_octave k a, transpose_octave k b)
| Par (a, b) -> Par (transpose_octave k a, transpose_octave k b)
| Repeat (n, m) -> Repeat (n, transpose_octave k m)
{ p with octave = … } is a functional record update: a new pitch that copies p and changes one field, while p itself is untouched. Every arm builds a new node from the old one; Rest _ -> m returns the rest itself, unchanged. The result shares every rest with the original and rebuilds every Seq and Par it visits, changed or not: session 2's persistent tree — sharing a subtree is free because nothing is ever mutated, but each rebuilt node is an allocation.
The type says nothing about a playable range, so transposing by ten octaves is allowed and produces frequencies no speaker reproduces. Whether a type should promise more than it does here is a session 9 question.
C2 — print
let rec pretty m =
match m with
| Note (d, p) -> Printf.sprintf "%s%d/%s" (string_of_note p.note) p.octave (string_of_duration d)
| Rest d -> "r/" ^ string_of_duration d
| Seq (a, b) -> pretty a ^ " " ^ pretty b
| Par (a, b) -> "(" ^ pretty a ^ " // " ^ pretty b ^ ")"
| Repeat (n, m) -> Printf.sprintf "[%s]x%d" (pretty m) n
This is a new operation: one function is added and nothing else in the file changes — the cheap direction of the lecture's table. The format is a tiny grammar, and it explains the parentheses: a sequence is written with spaces and no brackets, so a Par must bring its own, or C4/4 D4/4 // E4/4 would not say which notes the second voice plays against. A chord of three prints as ((C4/4 // E4/4) // G4/4); the nesting that voices chose is visible here, and only here.
C3 — retrograde
let rec retrograde m =
match m with
| Note _ | Rest _ -> m
| Seq (a, b) -> Seq (retrograde b, retrograde a) (* time reverses ... *)
| Par (a, b) -> Par (retrograde a, retrograde b) (* ... simultaneity does not *)
| Repeat (n, m) -> Repeat (n, retrograde m)
Time runs backwards: a Seq swaps its two halves and reverses each. Simultaneity is not a direction, so a Par keeps its two voices where they are and reverses each one. Two facts follow, and the crab canon depends on both: retrograde preserves length_in_beats, and it is an involution — retrograde (retrograde m) = m — so the theme played against its own retrograde ends exactly as it began, which the last C3 check listens for.
A subtlety: the notation reversed is not always the sound reversed
What we wrote is the retrograde of the notation, voice by voice. When the two voices of a Par have different lengths it is not the reversal of the sound. Take Par (q C 4 ++ q D 4, q E 4): C at beat 0, D at beat 1, E at beat 0. Our retrograde gives (D4/4 C4/4 // E4/4) — D at 0, C at 1, and E still at 0. Played backwards on tape, E would sound at beat 1, under the C. The two notions agree exactly when both voices are equally long, which holds for the chords and for Bach's canon, whose second voice is the first one's mirror image — but not for canon in tunes.ml, whose voices last 8 and 12 beats. The C3 check expects the notation's retrograde. Making them agree in general means padding the shorter voice with a rest at its front — and the gap may be a length no single duration names, which is the tie question below in another guise.
C4 — simplify
let rec simplify m =
match m with
| Repeat (1, m) -> simplify m (* one repetition is no repetition *)
| Repeat (n, Repeat (k, m)) -> simplify (Repeat (n * k, m)) (* a repeat of a repeat *)
| Repeat (n, m) -> Repeat (n, simplify m) (* the general arm, LAST *)
| Seq (a, b) -> Seq (simplify a, simplify b)
| Par (a, b) -> Par (simplify a, simplify b)
| Note _ | Rest _ -> m
Two rewrite rules and a walk over the rest of the tree. The order of the arms is the point, and the rule is more precise than "the special cases first". Patterns are tried top to bottom and the first that fits wins. Repeat (1, m) and Repeat (n, Repeat (k, m)) are both special cases of Repeat (n, m), so the general arm must come after them: put it first and it captures every Repeat, the compiler reports both rules as unused (section 04), and the checks fail with [C4/4]x1 and [[C4/4]x3]x2 left unsimplified. The two rules themselves may be in either order: Repeat (1, Repeat (k, m)) fits both, and both send it to the same place.
Both rules call simplify again on their result instead of returning it, because the result may itself be simplifiable: Repeat (2, Repeat (3, Repeat (4, x))) becomes Repeat (6, Repeat (4, x)), a repeat of a repeat, which becomes Repeat (24, x). One rewrite is rarely enough. Repeat (0, m) is left alone: it plays as nothing and could become an empty melody, if the type had one.
04 — what the compiler said
Two warnings, and what they teach
Warning 8, after B2: the checklist
Adding | Repeat of int * melody to the type and rebuilding, with no function touched yet:
File "melody.ml", lines 39-43, characters 2-36:
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched: Repeat (_, _)
File "melody.ml", lines 46-49, characters 2-36: (* length_in_beats *)
Warning 8 [partial-match]: ...
File "melody.ml", lines 67-71, characters 4-38: (* go, inside to_events *)
File "melody.ml", lines 78-82, characters 2-36: (* transpose_octave *)
File "melody.ml", lines 94-98, characters 2-36: (* pretty *)
File "melody.ml", lines 101-104, characters 2-36: (* retrograde *)
Six sites: every function that matches on melody, and not voices, which matches on a list. Dune compiles each module twice, to bytecode and to native code, so the six appear twice — twelve lines of warning, six things to fix. The dune file keeps warning 8 a warning rather than an error (-warn-error -a) so that the build succeeds and the list can be worked through one function at a time, with the checks running in between.
Warning 11, in C4: the arm that can never be reached
With the general Repeat (n, m) arm moved above the two rules:
File "melody.ml", line 124, characters 4-17:
124 | | Repeat (1, m) -> simplify m
^^^^^^^^^^^^^
Warning 11 [redundant-case]: this match case is unused.
File "melody.ml", line 125, characters 4-29:
125 | | Repeat (n, Repeat (k, m)) -> simplify (Repeat (n * k, m))
^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 11 [redundant-case]: this match case is unused.
The two warnings are the two checks the lecture called dual: warning 8 is a shape nobody handles, warning 11 is a handler no shape can reach. Both come from the same fact — the compiler can read the closed list of shapes — and neither exists for the object version of the same type, where the cases are spread over classes and a missing or unreachable one is found by running the program.
05 — the three questions
Worked answers to the homework questions
How would we model a tie?
A tie joins two notes of the same pitch into one sound: d4 ~ d16 is one D lasting five sixteenths, a length no single duration names. The first idea is a constructor in melody, Tie of melody * melody, but that is the wrong level. to_events would then have to merge two adjacent events into one, checking that they have the same pitch and that nothing lies between them: extra work, and a constructor that admits malformed values. The tie is a property of a duration, so it belongs in duration:
type duration =
| Whole | Half | Quarter | Eighth | Sixteenth | ThirtySecond
| Dotted of duration
| Tied of duration * duration (* d4 ~ d16 is Tied (Quarter, Sixteenth) *)
The cost is two arms, beats and string_of_duration, and the compiler names both. Nothing in melody or its functions changes, because none of them looks inside a duration. (Dotted d is then a special case, Tied (d, half d), and could go — or stay, as notation.) The rule: put the constructor at the level of the thing it modifies.
What would an empty melody be?
A constructor Empty in melody, with Seq (Empty, m) and Par (Empty, m) sounding like m: the unit for both operators. It is a legitimate addition, and it costs exactly what the lecture said a new kind costs. Every function gets an arm — count_notes Empty = 0, length_in_beats Empty = 0.0, go t Empty = [], t, transpose_octave and retrograde return it, simplify can now drop it: Seq (Empty, m) -> simplify m. One arm is not free: pretty Empty = "" makes pretty (q C 4 ++ Empty ++ q D 4) print two spaces, so the Seq arm must skip an empty side. That is the real shape of the expensive direction — not that the compiler cannot find the sites, but that some of them need thought.
What it buys: voices can take a plain list and fold with Empty as the starting value, Repeat (0, m) simplifies to Empty, and a tune can be built up from nothing in a loop. Whether that is worth a case in every function is a design decision; the type as shipped says no, and makes the empty chord unwritable instead.
Where does pretty live, in Java?
Three answers, corresponding to the rows and columns of the lecture's table.
| abstract class | abstract class Melody { abstract String pretty(); } and a pretty() body in each subclass — Note, Rest, Seq, Par, Repeat: five files. The operation is spread over the kinds. Adding Repeat is one new class and nothing else changes; adding retrograde touches all five. |
| sealed + records | sealed interface Melody permits Note, Rest, Seq, Par, Repeat, each a record, and pretty is one static method with a switch over the five patterns, which the compiler checks for exhaustiveness exactly as OCaml does. This is the OCaml file, in Java 21 syntax: adding an operation is one method, adding a kind makes every switch fail to compile until it is extended — warning 8, as an error. |
| visitor | The abstract-class layout with the operation pulled back out: an interface Visitor<R> with one visit per kind, an accept in each class, and pretty as a class PrettyVisitor implements Visitor<String>. The operation is one place again, at the price of one interface that every kind and every operation must know. Matching, done by hand — which is why Java 21's switch made it mostly unnecessary. |
06 — properties
Five things that are true of every melody
Each of these is one line in the toplevel, on any m from tunes.ml or our own. In session 5 a library will generate the melodies for checks of this kind.
count_notes m = List.length (to_events 120 m)
length_in_beats (transpose_octave k m) = length_in_beats m
length_in_beats (retrograde m) = length_in_beats m
retrograde (retrograde m) = m
to_events 120 (simplify m) = to_events 120 m
The last one is what simplify means: a different tree, the same sound. The first one is why count_notes counts a Repeat the way it does.