15-150: Principles of Functional Programming

Lecture 15: Functors

In today's lecture, we looked at a case study of a library for dictionaries implemented with binary search trees. Using the idea of structures and signatures from the last lecture, we saw that we could implement it as adhering to a DICT signature.

But, we may also want to be able to operate on dictionaries containing entries of arbitrary type. This presents an issue, as now common operations are relative to a comparison function. This forces us to thread through a comparison function with our dictionary operations, which is not just cumbersome, but potentially error-prone.

To fix this, we introduce the notion of type classes, which are particular APIs that a variety of types may choose to implement. One such example of a signature is the ORD signature, which describes types which admit a total order comparison function. It follows naturally that any type which implements ORD is one that could be a key for our polymorphic dictionaries.

We saw that this became useful with the new notion of functors, which are essentially higher-order modules--modules which may take in other modules as argument. Seen in this way, we could avoid our previous issues by implementing only a single functor which takes in a structure ascribing to ORD.

We then went over a couple of gotchas about using functors, such as syntactically sugared module arguments and where type clauses.

Slides