Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fmap with a maybe when a function uses IO

Tags:

haskell

I have a function that I want to use a Maybe val with. Usually I would do func <$> val. But now suppose that func uses the IO monad. func <$> val will return a Maybe (IO ()). So instead I had to define a new operator:

(<$$>) :: Monad m => (a -> m b) -> Maybe a -> m ()
(<$$>) func (Just val) = func val >> return ()
(<$$>) func Nothing    = return ()

So now I can write func <$$> val, but is there a better way to do it?

like image 397
Vlad the Impala Avatar asked Oct 02 '22 14:10

Vlad the Impala


1 Answers

mapM_ from Data.Foldable is probably the best match:

Prelude Data.Foldable> :set -XScopedTypeVariables
Prelude Data.Foldable> :t \f (a :: Maybe a) -> Data.Foldable.mapM_ f a
\f (a :: Maybe a) -> Data.Foldable.mapM_ f a
  :: Monad m => (a -> m b) -> Maybe a -> m ()

If you'd like a more specialised type there's also maybe:

Prelude> :t \f -> maybe (return ()) (f $)
\f -> maybe (return ()) (f $)
  :: Monad m => (a -> m ()) -> Maybe a -> m ()
like image 106
GS - Apologise to Monica Avatar answered Oct 04 '22 03:10

GS - Apologise to Monica