Mutable references

A TVar is a variable whose value can be changed.

TVar comes from the stm library. The ‘T’ in both ‘STM’ and ‘TVar’ stands for ‘transactional’, which refers to some impressive thread-safety properties of these variables. But this won’t matter until we fork some threads later on.

There are four important functions to remember when working with TVars:

  1. newTVar initializes a new variable. Here we initialize two variables, a = 3 and b = 5.
  1. readTVar returns the variable’s current value.

The printVars function reads and then prints the values of a and b. We will use it repeatedly to watch how these two variables change as the program runs.

  1. writeTVar assigns a new value to a variable. Here we reassign a with a new value of 7.
  1. modifyTVar' applies a function to a variable’s value. Here we apply the function (* 2) to double the value of b.

Mutable references can be passed as arguments to functions. Here we define two functions:

  • increment increases a variable’s value by one;

  • swap interchanges the values of two variables.

We increment a once, then increment b five times in a for loop.

And finally, we’ll swap the values of a and b.

Next: