SHARE
TWEET

Untitled

a guest Jan 21st, 2020 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Account where
  2.  
  3. import           Control.Applicative (liftA2)
  4. import           GHC.Conc (atomically, readTVar, TVar, writeTVar)
  5.  
  6. data Acct = Acct (TVar Int)
  7.  
  8. withdraw :: Acct -> Int -> STM ()
  9. withdraw (Acct tv) amount = do
  10.   balance <- readTVar tv
  11.   writeTVar tv $ balance - amount
  12.  
  13. transfer :: Acct -> Acct -> Int -> STM ()
  14. transfer a1 a2 amount = do
  15.     withdraw a1 amount
  16.     withdraw a2 $ -amount
  17.  
  18. mainSTM :: STM (Int, Int)
  19. mainSTM = do
  20.   acc1 <- newTVar 100 -- account with 100 shekels
  21.   acc2 <- newTVar 30 -- account with 30 shekels
  22.   transfer (Acct acc1) (Acct acc2) 15 -- transfer 15 shekels from acc1 to acc2
  23.   liftA2 (,) (readTVar acc1) (readTVar acc2) -- read values from each account
  24.  
  25. main :: IO ()
  26. main = do
  27.   (a, b) <- atomically mainSTM -- commit transaction
  28.   putStrLn $ "Account 1: " <> show a <> ", " <> "Account 2: " <> show b -- show result
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top