Last updated on

Week 8-9 Debrief: Post-midterm

Congrats on completing the midterm and the 9th week of CS-214! Here is a round-up of administrative notices, midterm takeaways, and interesting questions.

Administrivia

Interesting questions

Midterm takeaways

Whilst grading the midterm we identified some interesting patterns that we’d like to share with you as takeaways for the exam.

Code injection

Recall question 13 from subsection 3.3 From Higher-Order Functions to Recursion. It asked you to implement a more efficient center function.

The initial implementation is as follows:

def center(boids: Boids): Vector2 =
  boids.map(_.position).foldLeft(Zero)(_+_) / boids.length

The question provides a scaffold for the improved implementation, with the aim of traversing the list only once:

def centerRec(boids: Boids): Vector2 =
  def loop(rest: Boids)(...): ... =
    rest match
      case Nil => ...
      case head :: tail =>
        loop(tail)(...)
  loop(boids)(...)

A solution that traverses just once keeps a running total of the sum of the positions and of the number of observed boids. For example:

def centerRec(boids: Boids): Vector2 =
  def loop(rest: Boids)( ⟦sum: Vector2, count: Int⟧ ): ⟦Vector2⟧ =
    rest match
      case Nil => ⟦sum / count⟧
      case head :: tail =>
        loop(tail)( ⟦sum + head.position, count + 1⟧ )
  loop(boids)( ⟦Zero, 0⟧ )

However, it is also possible to fill in the holes such that the overall program is functionally correct, but not all individual snippets are valid expressions. This is reminiscent of an exploit called SQL injection. We were pleasantly surprised to see such creative solutions to the posed problem! Here is an example:

def centerRec(boids: Boids): Vector2 =
  def loop(rest: Boids)( ⟦sum: Vector2⟧ ): ⟦Vector2⟧ =
    rest match
      case Nil => ⟦sum⟧
      case head :: tail =>
        loop(tail)( ⟦sum + head.position⟧ )
  loop(boids)( ⟦Zero) / (boids.length⟧ )

Closely observe the parentheses in the outer-function’s hole. The expression Zero) / (boids.length incorrectly balances parentheses, but when substituted into the overall program, it works! Hurray! However, note that unfortunately the implementation using boids.length is not as efficient, as List.length traverses the linked list again to compute the length.

Spec-driven development

Questions 36 and 37 from subsection 6.3: Search asked you to implement functions to enumerate all tours, and find the shortest perfect tour. Being part of section 6: Specifications, the functions to implement are annotated with require and ensuring – stating the pre- and post-conditions, respectively. These can help guide your implementation. Question 36, for example, stated the following ensuring:

ensuring { tours =>
  tours.forall: (tour, _) =>
    tour.rooted(first) && tour.exhaustive(rest + first) && tour.parsimonious  
}

In particular the ensuring clause can be useful to sanity check your implementation against. Some submissions unfortunately only covered the post-condition partially (e.g. left out tour.parsimonious), whereas they could have been fixed easily when compared against the spec.

Type variables

Recall section 4: Variance. Question 21 asked you to implement a small program which fails at runtime, if the compiler were to accept programs with invalid type variance.

The trait is defined as follows:

trait Printer[+A]:
    def show[B <: A](b: B): String

2026-11-13/midterm.worksheet.sc

A handful of submissions contained something like the following snippet:

object IntPrinter extends Printer[Any]:
    def show[Int <: Any](i: Int): String = (i+1).toString

2026-11-13/midterm.worksheet.sc

Whilst it might look like we match on the type variable being Int, what this actually does is create a new type variable with the name Int. As such, the value i: Int is not of the usual integer type, but rather an instance of some arbitrary type that is a subtype of Any (which any type satisfies). The syntax is such that the name on the left-hand side of <: is a new type variable, and the expression on the right-hand side is already a valid type expression. Therefore, this code is equivalent to:

object IntPrinter2 extends Printer[Any]:
    def show[B <: Any](b: B): String = (b+1).toString

2026-11-13/midterm.worksheet.sc

Stable identifier pattern matching

In question 31 of section 6.2: Specification you were asked to check whether a tour is “rooted” at a given landmark; that is, whether it starts at that landmark.

A solution might implement this by checking that the tour is non-empty and the first stop is indeed the given landmark.

extension (tour: Tour)
  def rooted(at: Landmark): Boolean =
    match tour with
    | Nil => false
    | hd :: _ => hd == at

2026-11-13/midterm.worksheet.sc

A few solutions attempted to inline the equality into the pattern matching:

extension (tour: Tour)
  def rooted(at: Landmark): Boolean =
    match tour with
    | at :: _ => true
    | _ => false

2026-11-13/midterm.worksheet.sc

Whilst the idea is neat, unfortunately this particular program does not have the intended effect. The pattern matching syntax is such that the names in the patterns are fresh variable names. Therefore, at inside the pattern match has nothing to do with the at argument of the function.

However, Scala supports stable identifier patterns! The syntax is to use `variable_name`:

extension (tour: Tour)
  def rooted(at: Landmark): Boolean =
    match tour with
    | `at` :: _ => true
    | _ => false

2026-11-13/midterm.worksheet.sc

Now, if the head of the list is equal to at, it will return true, and false otherwise.

Set ordering

Question 33 – also part of the section on specifications – asked you to implement a check that a tour is parsimonious; that is, it never visits a landmark twice. A few submissions relied on sets to obtain the distinct landmarks in a route, and then check whether the route is exactly the distinct landmarks on the route.

extension(tour: Tour)
  def parsimonious: Boolean =
    tour.toSet.toList == tour

Whilst tour.toSet contains precisely the distinct elements in tour, it is not guaranteed to be equal to tour, even if tour does not contain duplicates. The reason is that the contract of Set does not guarantee an ordering. The expression List(1, 2, 3).toSet.toList might well evaluate to List(2, 3, 1) according to the contract. One correct solution is to instead check that the length of the set is equal to the length of the list.

That being said, what does List.toSet.toList actually evaluate to?

Spoiler: for lists with less than five distinct elements, List.toSet is actually ordered, so List(1, 2, 3).toSet.toList = List(1, 2, 3)!

It’s a good exercise to jump into the Scala List implementation to see why this is the case, but below is an explanation.

What does List.toSet actually evaluate to?

Peeking into List.toSet we find that it uses Set.from, which in turn uses the SetBuilderImpl class from Set. In Set.from it calls the builder’s addAll to insert all elements from the original list.

The builder class initialises the accumulating set elems to the empty set. It uses a special immutable EmptySet class for this, which is an optimised implementation for empty sets: size returns the 0 constant, isEmpty returns the true constant, contains(x) returns the false constant.

Through a few indirections in SetBuilderImpl’s parent classes, addAll(xs) actually calls the builder’s addOne(x) repeatedly. So, how does that function work? Here’s a simplified version of the implementation:

def addOne(elem: A) =
  if (elems.size < 4) {
    elems = elems + elem
  } else {
    if (!switchedToHashSetBuilder) {
      switchedToHashSetBuilder = true
      hashSetBuilder = new HashSetBuilder
      elems.buildTo(hashSetBuilder)
    }
    hashSetBuilder.addOne(elem)
  }

For the first four elements it simply adds to the accumulating set, but afterwards it switches to a hash set builder. The initial set type is EmptySet (hard-coded to have 0 elements). The result of EmptySet.addOne is a different specialised type Set1 for singleton sets. The result of Set1.addOne is yet another specialised type Set2 for two-element sets. And so forth, all the way to Set4.

Once we’re pushing our fifth distinct element, we start building a HashSet instead. Since it relies on hash values of the elements, its elements are not ordered.

Indeed, List(1, 2, 3, 4).toSet.toList == List(1, 2, 3, 4), but List(1, 2, 3, 4, 5).toSet.toList == List(5, 1, 2, 3, 4).

Code quality improvements

Here are a few common code smells and code style improvements, based on your lab submissions:

Explicit maps over enum values

Sometimes it is fine to list enum constructors “by hand”. There is no need to be generic and iterate over .values, especially when the logic for each constructor is different.

A match would have been useful to extract or destructure inner values, but here the constructors carry none. Iterating over .values with a for comprehension only to immediately match on every case adds boilerplate without making the code more generic:

Before:

(for
  move <- BloxorzMove.values
  s = move match
    case BloxorzMove.Left  => state.left
    case BloxorzMove.Right => state.right
    case BloxorzMove.Up    => state.up
    case BloxorzMove.Down  => state.down
yield (move, s)).toMap

2026-11-13/smells.worksheet.sc

Writing a direct Map literal is cleaner, more readable and just as exhaustive:

After:

Map(
  BloxorzMove.Left  -> state.left,
  BloxorzMove.Right -> state.right,
  BloxorzMove.Up    -> state.up,
  BloxorzMove.Down  -> state.down,
)

2026-11-13/smells.worksheet.sc

Map supports filter

List and Map are both Iterable, they share the same collection combinators: map, filter, flatMap and more. Converting a Map to a List just to call .filter, then back to a Map, suggests a misconception that filtering is a List-specific operation.

Before:

physicalNeighbors(state)
  .toList
  .filter((_, s) => isLegal(s))
  .toMap

2026-11-13/smells.worksheet.sc

After:

physicalNeighbors(state)
  .filter((_, s) => isLegal(s))

2026-11-13/smells.worksheet.sc

Keep lazy lists lazy

Any computation placed before a #:: is evaluated eagerly when the function is called, regardless of whether the caller ever asks for more than the current element (or even asks for any elements at all).

In the example below, expensiveNext(n) is computed immediately before #::, evaluating the next step upfront:

Before:

def numbers(n: Int): LazyList[Int] =
  val next = expensiveNext(n) // evaluated eagerly, even if the caller only touches `n`!
  n #:: numbers(next)

2026-11-13/smells.worksheet.sc

The fix is to move everything after the head inside the #:: { ... } tail block so it is evaluated strictly on demand:

After:

def numbers(n: Int): LazyList[Int] =
  n #:: {
    val next = expensiveNext(n)
    numbers(next)
  }

2026-11-13/smells.worksheet.sc

A checklist for keeping lazy lists lazy: