Last active
July 14, 2017 05:02
-
-
Save koterpillar/844545a40ca1c74c506b064c01568076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Concurrent.STM | |
import qualified Data.Map as M | |
import Data.Maybe | |
main = do | |
pendingV <- atomically $ newTVar M.empty | |
let handleFst (key, ourVal) = | |
atomically $ do | |
pending <- readTVar pendingV | |
case M.lookup key pending of | |
Just (Right theirVal) -> return $ Just (ourVal, theirVal) | |
_ -> do | |
writeTVar pendingV $ M.insert key (Left ourVal) pending | |
return Nothing | |
let handleSnd (key, ourVal) = | |
atomically $ do | |
pending <- readTVar pendingV | |
case M.lookup key pending of | |
Just (Left theirVal) -> return $ Just (theirVal, ourVal) | |
_ -> do | |
writeTVar pendingV $ M.insert key (Right ourVal) pending | |
return Nothing | |
results <- | |
sequence | |
[ handleFst (1, "a1") | |
, handleSnd (2, True) | |
, handleSnd (1, False) | |
, handleFst (2, "a2") | |
] | |
print $ catMaybes results | |
return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment