Mutable State
Typing relation. Usually written
Anonymous function.
Type abstraction.
Function type.
Subtyping relation.
Read
In previous notes, we introduced IMP
.
IMP
is a very simple language—it has a single global scope and variables in that scope are mutable.
When we discussed functional programming, did it in the context of FL
, which has first-class functions but does not have mutable state.
This was a deliberate choice: it's surprisingly tricky to include mutable state and first-class functions in the same language.
In this section, we'll extend FL
with mutable state in the form of reference cells (aka ref cells or references).
A ref cell is a new kind of value that acts like a mutable container.
Ref cells have three associated operations:
- Create:
creates a cell that contains the value of . - Read: If
evaluates to a reference cell, then returns its contents. - Write: If
evaluates to a reference cell , then replaces the contents of with the value of .FL
is an expression oriented language; unlikeIMP
, it doesn't separate expressions from statements.
Ref cells are not very expressive on their own, but adding them to FL
forces us to deal with the problems of mutable state.
In combination of other features like records, ref cells allow us to implement a wide variety of mutable data structures.