Transformers Monad vs Monad

"Monads allow the programmer to build computations using sequential building blocks," so he allows some computations to be combined. If so, then why the following code cannot 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 can't we put different functions in a monad (as in the example above)?

  • Why do we need an additional layer, i.e. Transformers for combining monads?

+4
source share
1 answer

Monad transformers are mechanisms for placing various functions in a monad.

, , . I/O State, StateT s IO a. liftIO , 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.."
+8

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


All Articles