Skip to content

Instantly share code, notes, and snippets.

@solidsnack
Forked from scan/chan.hs
Last active December 11, 2015 18:48
Show Gist options
  • Save solidsnack/4643746 to your computer and use it in GitHub Desktop.
Save solidsnack/4643746 to your computer and use it in GitHub Desktop.
Use of `maybe` combinator.
import Control.Applicative
import Control.Concurrent.Chan (Chan, newChan)
import qualified Data.Map as M
import Control.Concurrent.STM (atomically, TVar, readTVar, writeTVar)
import Control.Monad.Trans
type Id = Integer
getOrCreateChannel :: (MonadIO m) => Id -> TVar (M.Map Id (Chan a)) -> m (Chan a)
getOrCreateChannel cid t = liftIO $ do
nchan <- newChan
atomically $ do
chans <- readTVar t
maybe (nchan <$ writeTVar t (M.insert cid nchan chans))
return
(M.lookup cid chans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment