Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monad transformers monad duplication

I am new to monad transformers, so sorry easy question. I have value val :: MaybeT IO String and function fn :: String -> IO [String]. So after binding, I have val >>= liftM fn :: MaybeT IO (IO [String]). How can I remove duplicate IO monad and get result of type MaybeT IO [String]?

like image 247
KAction Avatar asked May 19 '13 17:05

KAction


People also ask

Why use monad transformers?

Monad transformers not only make it easier to write getPassphrase but also simplify all the code instances.

What is liftIO?

liftIO allows us to lift an IO action into a transformer stack that is built on top of IO and it works no matter how deeply nested the stack is.

What is the reader monad?

The Reader monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, pass values from function to function, and execute sub-computations in a modified environment. Using Reader monad for such computations is often clearer and easier than using the State monad.

What is state monad?

The state monad is a built in monad in Haskell that allows for chaining of a state variable (which may be arbitrarily complex) through a series of function calls, to simulate stateful code. It is defined as: newtype State s a = State { runState :: (s -> (a,s)) }


1 Answers

Use lift (or liftIO) instead of liftM.

> :t val >>= lift . fn
val >>= lift . fn :: MaybeT IO [String]

liftM is for applying pure functions in a monad. lift and liftIO are for lifting actions into a transformer.

liftM  :: Monad m => (a -> b) -> m a -> m b
lift   :: (Monad m, MonadTrans t) => m a -> t m a
liftIO :: MonadIO m => IO a -> m a
like image 196
hammar Avatar answered Sep 29 '22 09:09

hammar