packages feed

mortred-0.0.1: src/Mortred/Utilities.hs

module Mortred.Utilities where

import RIO

-- | Re-throws an exception after applying a transformation from one exception type to another.
mapExceptionM :: (Exception e1, Exception e2, MonadUnliftIO m) => (e1 -> e2) -> m a -> m a
mapExceptionM f = handle (f >>> throwIO)

-- | Takes a 'Maybe' and turns it into an 'Either', with an error value for when the 'Maybe' is
-- 'Nothing'.
note :: e -> Maybe a -> Either e a
note _e (Just a) = Right a
note e Nothing = Left e

-- | Takes a monadic action producing a @m Maybe@ and throws a given exception @e@ from it. This
-- is just a specialization of @'fromEitherM' '$' note e '<$>' action@.
fromMaybeM :: (Exception e, MonadUnliftIO m) => e -> m (Maybe a) -> m a
fromMaybeM e = fmap (note e) >>> fromEitherM

-- | Lifted version of 'Data.List.find'.
findM :: (Monad m) => (a -> m Bool) -> [a] -> m (Maybe a)
findM _p [] = pure Nothing
findM p (a : as) = do
  result <- p a
  if result then pure (Just a) else findM p as