简体   繁体   中英

Monad vs Monad transformers

"Monads allow the programmer to build up computations using sequential building blocks" therefore it allows us to combine some computations. If this is the case, then why the following code can not be run?

import Control.Monad.Trans.State

gt :: State String String
gt = do
   name <- get
   putStrLn "HI" -- Here is the source of problem!
   put "T"
   return ("hh..." ++ name ++ "...!")


main= do
  print $ execState gt "W.."
  print $ evalState gt "W.."
  • Why cannot we put different functions in a monad (like the above example)?

  • Why do we need an additional layer, ie transformers to combine the monads?

Monad transformers are the mechanisms for putting different functions in a monad.

A monad only knows how to combine computations that are within the abilities of that monad. You can't do I/O in a State monad, but you can in a StateT s IO a monad. However, you will need to use liftIO on the computations that do I/O.

import Control.Monad.Trans.State
import Control.Monad.IO.Class (liftIO)

gt :: StateT String IO String
gt = do
   name <- get
   liftIO $ putStrLn "HI"
   put "T"
   return ("hh..." ++ name ++ "...!")


main = do
  print =<< execStateT gt "W.."
  print =<< evalStateT gt "W.."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM