{-# LANGUAGE Safe #-}
-------------------------------------------------------------------------------
-- |
-- Module      :  BroadcastChan.Prelude
-- Copyright   :  (C) 2014-2021 Merijn Verstraaten
-- License     :  BSD-style (see the file LICENSE)
-- Maintainer  :  Merijn Verstraaten <merijn@inconsistent.nl>
-- Stability   :  experimental
-- Portability :  haha
--
-- This module contains convenience functions that clash with names in
-- "Prelude" and is intended to be imported qualified.
-------------------------------------------------------------------------------
module BroadcastChan.Prelude
    ( forM_
    , mapM_
    ) where

import Prelude hiding (mapM_)
import Control.Monad.IO.Unlift (MonadIO(..))

import BroadcastChan

-- | 'mapM_' with it's arguments flipped.
forM_ :: MonadIO m => BroadcastChan Out a -> (a -> m b) -> m ()
forM_ :: BroadcastChan Out a -> (a -> m b) -> m ()
forM_ = ((a -> m b) -> BroadcastChan Out a -> m ())
-> BroadcastChan Out a -> (a -> m b) -> m ()
forall a b c. (a -> b -> c) -> b -> a -> c
flip (a -> m b) -> BroadcastChan Out a -> m ()
forall (m :: * -> *) a b.
MonadIO m =>
(a -> m b) -> BroadcastChan Out a -> m ()
mapM_

-- | Map a monadic function over the elements of a 'BroadcastChan', ignoring
-- the results.
mapM_ :: MonadIO m => (a -> m b) -> BroadcastChan Out a -> m ()
mapM_ :: (a -> m b) -> BroadcastChan Out a -> m ()
mapM_ a -> m b
f BroadcastChan Out a
ch = do
    Maybe a
result <- IO (Maybe a) -> m (Maybe a)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Maybe a) -> m (Maybe a)) -> IO (Maybe a) -> m (Maybe a)
forall a b. (a -> b) -> a -> b
$ BroadcastChan Out a -> IO (Maybe a)
forall (m :: * -> *) a.
MonadIO m =>
BroadcastChan Out a -> m (Maybe a)
readBChan BroadcastChan Out a
ch
    case Maybe a
result of
        Maybe a
Nothing -> () -> m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        Just a
x -> a -> m b
f a
x m b -> m () -> m ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> (a -> m b) -> BroadcastChan Out a -> m ()
forall (m :: * -> *) a b.
MonadIO m =>
(a -> m b) -> BroadcastChan Out a -> m ()
mapM_ a -> m b
f BroadcastChan Out a
ch