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.
newTVarinitializes a new variable. Here we initialize two variables,
a = 3and
b = 5.
readTVarreturns the variable’s current value.
printVars function reads and then prints the values of
b. We will use it repeatedly to watch how these two variables change as the program runs.
writeTVarassigns a new value to a variable. Here we reassign
awith a new value of
modifyTVar'applies a function to a variable’s value. Here we apply the function
(* 2)to double the value of
Mutable references can be passed as arguments to functions. Here we define two functions:
incrementincreases a variable’s value by one;
swapinterchanges the values of two variables.
a once, then increment
b five times in a for loop.