4

"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, i.e. transformers to combine the monads?

duplode
34.5k7 gold badges88 silver badges159 bronze badges
asked Jul 13, 2017 at 13:32
0

1 Answer 1

8

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.."
answered Jul 13, 2017 at 13:55
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer! Could you please tell me why you used =<< in the last two lines?
execStateT and evalStateT both return an IO String here, and you probably want to print the String inside them. =<< calls a function on the left using the inner value of the monad on the right.
@4xx This equivalent version might be more familiar to you: main = do x <- execStateT gt "W.." ; print x ; y <- evalStateT gt "W.." ; print y
Is your answer for the standard monads, like IO, State, etc or it's generic. I wondered if we can have a function (or monad) that performs series of arbitrary functions (computations) sequentially on an input?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.