State Monad: a model of a volatile state
The state monad is a purely functional environment for state programs with a simple API:
Documentation in the mtl package .
State monad is usually used when it requires a state in a single control flow. It actually does not use a volatile state in its implementation. Instead, the program is parameterized with a state value (i.e., State is an additional parameter for all calculations). The state only seems to be mutated in one thread (and cannot be shared between threads).
Convent ST and STRefs
The ST monad is a limited cousin of the IO monad.
It allows an arbitrary mutable state implemented as an actual mutable memory on a machine. The API becomes safe in programs without side effects, since a rank-2 parameter prohibits values โโthat depend on the changing state from shielding the local area.
Thus, it allows you to control the variability in other clean programs.
Commonly used for mutable arrays and other data structures that are mutated and then frozen. It is also very effective, since the volatile state is "hardware acceleration."
Primary API:
- Control.Monad.ST
- runST - start a new calculation of the memory effect.
- And STRefs : pointers to (local) mutable cells.
- ST-based arrays (such as a vector) are also widespread.
Think of it as a less dangerous brother from the IO monad. Or IO, where you can only read and write to memory.
IORef: STRIF in IO
This is STREF (see above) in the IO monad. They do not have the same security guarantees, such as STRef on locality.
MVars: IORef with locks
Like STRefs or IORefs, but with an attached lock for secure simultaneous access from multiple threads. IORefs and STRef are safe only with multi-threaded configuration when using atomicModifyIORef (comparison and replacement operation). MVars is a more general mechanism for the secure exchange of mutable state.
Typically, in Haskell, use MVars or TVars (STM mutable cells), on top of STRef or IORef.
Don Stewart Apr 04 2018-11-11T00: 00Z
source share