Skip to content

Commit

Permalink
MonadAsync: added ConcurrentlyM
Browse files Browse the repository at this point in the history
  • Loading branch information
coot committed Jun 25, 2020
1 parent 85d962c commit 2cf9686
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion io-sim-classes/src/Control/Monad/Class/MonadAsync.hs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module Control.Monad.Class.MonadAsync
, MonadAsyncSTM (..)
, AsyncCancelled(..)
, ExceptionInLinkedThread(..)
, ConcurrentlyM (..)
, link
, linkTo
, linkOnly
Expand All @@ -20,8 +21,10 @@ module Control.Monad.Class.MonadAsync

import Prelude hiding (read)

import Control.Applicative (Alternative (..), liftA2)
import Control.Monad.Class.MonadFork
import Control.Monad.Class.MonadSTM
import Control.Monad.Class.MonadTimer
import Control.Monad.Class.MonadThrow

import Control.Concurrent.Async (AsyncCancelled (..))
Expand Down Expand Up @@ -186,6 +189,43 @@ class ( MonadSTM m
withAsync right $ \b ->
waitBoth a b

-- | Similar to 'Async.Concurrently' but which works for any 'MonadAsync'
-- instance.
--
newtype ConcurrentlyM m a = ConcurrentlyM { runConcurrentlyM :: m a }

instance Functor m => Functor (ConcurrentlyM m) where
fmap f (ConcurrentlyM ma) = ConcurrentlyM (fmap f ma)

instance ( Applicative m
, MonadAsync m
) => Applicative (ConcurrentlyM m) where
pure = ConcurrentlyM . pure

ConcurrentlyM fn <*> ConcurrentlyM as =
ConcurrentlyM $
(\(f, a) -> f a)
`fmap`
concurrently fn as

instance ( Alternative m
, MonadAsync m
, MonadTimer m
) => Alternative (ConcurrentlyM m) where
empty = ConcurrentlyM $ forever (threadDelay 86400)
ConcurrentlyM as <|> ConcurrentlyM bs =
ConcurrentlyM $ either id id <$> as `race` bs

instance ( Semigroup a
, MonadAsync m
) => Semigroup (ConcurrentlyM m a) where
(<>) = liftA2 (<>)

instance ( Monoid a
, MonadAsync m
) => Monoid (ConcurrentlyM m a) where
mempty = pure mempty

--
-- Instance for IO uses the existing async library implementations
--
Expand All @@ -203,7 +243,7 @@ instance MonadAsyncSTM Async.Async STM.STM where

instance MonadAsync IO where

type Async IO = Async.Async
type Async IO = Async.Async

async = Async.async
asyncThreadId = \_proxy -> Async.asyncThreadId
Expand Down

0 comments on commit 2cf9686

Please sign in to comment.