Apply function to value inside IO

I have a type function a -> IO (Maybe b), and I want to apply it to IO (Maybe a)and get IO (Maybe b). I wrote a function for this:

ioMaybeApply :: (a -> IO (Maybe b)) -> IO (Maybe a) -> IO (Maybe b)
ioMaybeApply f ioMaybeA = do
  maybeA <- ioMaybeA
  maybe (return Nothing) f maybeA

Is there a standard Haskell function for this? I tried to search using Google, but I did not find anything. If not, is my implementation good, or could it be easier?

+4
source share
1 answer

This can be achieved with MaybeTmonad transformer :

GHCi> import Control.Monad.Trans.Maybe
GHCi> :t \f m -> runMaybeT (MaybeT m >>= MaybeT . f)
\f m -> runMaybeT (MaybeT m >>= MaybeT . f)
  :: Monad m => (a1 -> m (Maybe a)) -> m (Maybe a1) -> m (Maybe a)
import Control.Monad.Trans.Maybe

-- Making it look like your definition, for the sake of comparison.
ioMaybeApply :: (a -> IO (Maybe b)) -> IO (Maybe a) -> IO (Maybe b)
ioMaybeApply f ioMaybeA = runMaybeT $ do
  a <- MaybeT ioMaybeA
  MaybeT (f a)

, , , , a -> IO (Maybe b) a -> MaybeT IO b - (>>=) / do - . , , , MaybeT ; .

( , , , Compose, Functor Applicative, Monad, -, Monad. , , .)

+6

Source: https://habr.com/ru/post/1674893/


All Articles