-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmutable-references.hs
More file actions
44 lines (34 loc) · 946 Bytes
/
mutable-references.hs
File metadata and controls
44 lines (34 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import Control.Monad.STM
import Control.Concurrent.STM.TVar
import Data.Foldable (for_)
main =
do
a <- atomically (newTVar 3)
b <- atomically (newTVar 5)
let
printVars label =
do
x1 <- atomically (readTVar a)
x2 <- atomically (readTVar b)
putStrLn ("a = " ++ show x1 ++ ", b = " ++ show x2
++ " (" ++ label ++ ")")
printVars "initial values"
atomically (writeTVar a 7)
printVars "changed a to 7"
atomically (modifyTVar' b (* 2))
printVars "doubled b"
let
increment ref = atomically (modifyTVar' ref (+ 1))
swap ref1 ref2 =
atomically $
do
x1 <- readTVar ref1
x2 <- readTVar ref2
writeTVar ref1 x2
writeTVar ref2 x1
increment a
for_ [1..5] $ \_ ->
increment b
printVars "incremented"
swap a b
printVars "swapped"