Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Account where
- import Control.Applicative (liftA2)
- import GHC.Conc (atomically, readTVar, TVar, writeTVar)
- data Acct = Acct (TVar Int)
- withdraw :: Acct -> Int -> STM ()
- withdraw (Acct tv) amount = do
- balance <- readTVar tv
- writeTVar tv $ balance - amount
- transfer :: Acct -> Acct -> Int -> STM ()
- transfer a1 a2 amount = do
- withdraw a1 amount
- withdraw a2 $ -amount
- mainSTM :: STM (Int, Int)
- mainSTM = do
- acc1 <- newTVar 100 -- account with 100 shekels
- acc2 <- newTVar 30 -- account with 30 shekels
- transfer (Acct acc1) (Acct acc2) 15 -- transfer 15 shekels from acc1 to acc2
- liftA2 (,) (readTVar acc1) (readTVar acc2) -- read values from each account
- main :: IO ()
- main = do
- (a, b) <- atomically mainSTM -- commit transaction
- putStrLn $ "Account 1: " <> show a <> ", " <> "Account 2: " <> show b -- show result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement