15-150: Principles of Functional Programming

Lecture 19: Imperative Programming

In this lecture, we finally lifted the wool from over your eyes and revealed that there are in fact ways to imperatively program in SML.

While in functional programmimng we typically eschew the usage of effects for more predictable and safe immutable code, the lesson is that no dogma is worth contorting yourself over to satisfy--not using mutability is recommended, but not always necessary. We have been hiding the presence of ref cells for the right time.

In SML, a value of type t ref is a mutable ref cell which holds a value of type t. This is mutable, meaning that even if we assign the value of a ref cell to a given value, the value that is stored inside of the box might change over time, meaning that we can potentially write impure functions which return different outputs on the same input.

We discussed the possibility of aliasing, where two variables holding the same ref cell might potentially see the same values. We saw that we could use ref cells to implement functions we have seen before without using direct recursive results, and that we could implement certain handy idioms like generating fresh identifiers and backpatching function definitions via hooks.

Mutability is useful in small doses. Usually, so long as our functions are observationally pure, meaning that they may employ impure components but overall provide a pure API, we are just fine.

Slides