= Solution
Use an <F-bounded polymorphism> constraint to make comparisons with another `T` available:
``
trait Ordered[T] {
def <(that: T): Boolean
}
class MinMSet[T <: Ordered[T]](contents: List[T])
extends MSet[T](contents) {
def min: T = {
if (data.isEmpty) throw new NoSuchElementException("MinMSet.min")
var best = data.head
var rest = data.tail
while (rest.nonEmpty) {
if (rest.head < best) best = rest.head
rest = rest.tail
}
best
}
}
``
The <upper type bound> `T <: Ordered[T]` guarantees the method signature needed for `rest.head < best`. Assuming that comparison implements the intended total ordering, the <loop invariant> says `best` is a minimum of the inspected prefix; the remaining suffix length decreases. The method returns a minimum in $O(N)$ comparisons and $O(1)$ auxiliary space, without deleting it. The bound supplies a comparison operation, not a proof of its order laws.
Back to article page