I'm new to Haskell and STM and I'm trying to understand the basics concept.
In Haskell and Functional Programming in general,correct me if I'm wrong, there's no such thing like assignment.
I cannot write x=3;
all I can do is generate an other binding with x
and 3
.
Now when it comes to TVar and threads, if I have a number of threads sharing the same TVar, if one thread changes the value, with writeTVar
, the others thread will see the changed value, am I right?
So if I have 2 thread sharing the same TVar Int
var, and the first one add 1 to it, in case of success, the second thread will see the updated value?
Thaks
It may be better to consider TVar
not a variable, but a channel you can read from and write to.
A pure variable may be considered a pure function which always returns some value (and this value is bound only once, like in your example).
A variable/function in a monad has some "context" (that's what monads are for), that may change its value (e.g. randomIO :: Random a => IO a
from System.Random
may be considered a "monadic value", value, which may be changed on any call).
Reading and writing to TVar
are explicit operations that are not pure, that's why functions readTVar
/writeTVar
are wrapped into STM
monad, they depend on some hidden context, which may change the result (making value transfer possible between threads). That bounds these operations into STM
monad though, which can be escaped to IO
only.