54

I am new to Haskell but understand how Monad Transformers can be used. Yet, I still have difficulties grabbing their claimed advantage over passing parameters to function calls.

Based on the wiki Monad Transformers Explained, we basically have a Config Object defined as

data Config = Config Foo Bar Baz

and to pass it around, instead of writing functions with this signature

client_func :: Config -> IO ()

we use a ReaderT Monad Transformer and change the signature to

client_func :: ReaderT Config IO ()

pulling the Config is then just a call to ask.

The function call changes from client_func c to runReaderT client_func c

Fine.

But why does this make my application simpler ?

1- I suspect Monad Transformers have an interest when you stitch a lot of functions/modules together to form an application. But this is where is my understanding stops. Could someone please shed some light?

2- I could not find any documentation on how you write a large modular application in Haskell, where modules expose some form of API and hide their implementations, as well as (partly) hide their own States and Environments from the other modules. Any pointers please ?

(Edit: Real World Haskell states that ".. this approach [Monad Transformers] ... scales to bigger programs.", but there is no clear example demonstrating that claim)

EDIT Following Chris Taylor Answer Below

Chris perfectly explains why encapsulating Config, State,etc... in a Transformer Monad provides two benefits:

  1. It prevents a higher level function from having to maintain in its type signature all the parameters required by the (sub)functions it calls but not required for its own use (see the getUserInput function)
  2. and as a consequence makes higher level functions more resilient to a change of the content of the Transformer Monad (say you want to add a Writer to it to provide Logging in a lower level function)

This comes at the cost of changing the signature of all functions so that they run "in" the Transformer Monad.

So question 1 is fully covered. Thank you Chris.

Question 2 is now answered in this SO post

asked Oct 19, 2012 at 6:13
1
  • 4
    Transformers are also useful when you want the features of some monad temporarily, for a sub-computation. For example, I’ve used WriterT to log information while updating a data structure with unique identifiers generated using State. Commented Oct 19, 2012 at 8:18

1 Answer 1

51

Let's say that we're writing a program that needs some configuration information in the following form:

data Config = C { logFile :: FileName }

One way to write the program is to explicitly pass the configuration around between functions. It would be nice if we only had to pass it to the functions that use it explicitly, but sadly we're not sure if a function might need to call another function that uses the configuration, so we're forced to pass it as a parameter everywhere (indeed, it tends to be the low-level functions that need to use the configuration, which forces us to pass it to all the high-level functions as well).

Let's write the program like that, and then we'll re-write it using the Reader monad and see what benefit we get.

Option 1. Explicit configuration passing

We end up with something like this:

readLog :: Config -> IO String
readLog (C logFile) = readFile logFile
writeLog :: Config -> String -> IO ()
writeLog (C logFile) message = do x <- readFile logFile
 writeFile logFile $ x ++ message
getUserInput :: Config -> IO String
getUserInput config = do input <- getLine
 writeLog config $ "Input: " ++ input
 return input
runProgram :: Config -> IO ()
runProgram config = do input <- getUserInput config
 putStrLn $ "You wrote: " ++ input

Notice that in the high level functions we have to pass config around all the time.

Option 2. Reader monad

An alternative is to rewrite using the Reader monad. This complicates the low level functions a bit:

type Program = ReaderT Config IO
readLog :: Program String
readLog = do C logFile <- ask
 readFile logFile
writeLog :: String -> Program ()
writeLog message = do C logFile <- ask
 x <- readFile logFile
 writeFile logFile $ x ++ message

But as our reward, the high level functions are simpler, because we never need to refer to the configuration file.

getUserInput :: Program String
getUserInput = do input <- getLine
 writeLog $ "Input: " ++ input
 return input
runProgram :: Program ()
runProgram = do input <- getUserInput
 putStrLn $ "You wrote: " ++ input

Taking it further

We could re-write the type signatures of getUserInput and runProgram to be

getUserInput :: (MonadReader Config m, MonadIO m) => m String
runProgram :: (MonadReader Config m, MonadIO m) => m ()

which gives us a lot of flexibility for later, if we decide that we want to change the underlying Program type for any reason. For example, if we want to add modifiable state to our program we could redefine

data ProgramState = PS Int Int Int
type Program a = StateT ProgramState (ReaderT Config IO) a

and we don't have to modify getUserInput or runProgram at all - they'll continue to work fine.

N.B. I haven't type checked this post, let alone tried to run it. There may be errors!

answered Oct 19, 2012 at 8:09
Sign up to request clarification or add additional context in comments.

17 Comments

Thank you Chris. It makes perfect sense and perfectly describes the 'hiding effect' benefit. It also raises a couple of additional questions on the rules functions signatures in a large App should obey as well as the general structure of the App. I propose to let the question run for a few hours to see if we get more input. I will then come back with a better formalization of any remaining request for clarification.
It should be getUserInput :: (MonadReader Config m, MonadIO m) => m String (and you'll need FlexibleContexts enabled). Also, all of the functions called by the generalized function need the generalized type too. The generalized type is bigger than the specific type, and you can't fit a big type into a small type (but you can fit a small type into a big type at the top, when you call runProgram with a specific Monad).
@alinsoar I think the best monad tutorial is "You could have invented monads (and maybe you already have)" which is found here. The same author has a post on monad transformers as well, which I seem to remember was pretty good.
@alinsoar Scala has monads (called for comprehensions) and you can use them in OCaml as well (with a module instead of a type class) although I believe the syntax is not as nice. Python has list comprehensions and generator comprehensions, which you could think of as an implementation of the list monad (although it allows you to do IO as well). As you said, you can implement monads in any language, but without type classes, parametric polymorphism and built-in syntax for them, it is a bit clunky.
@alinsoar The only way to get more experience is to get more experience. There's no magic route to understanding any programming language. Just use the language to solve problems, read books, articles and papers about it, and ask/answer questions on Stack Overflow. Understanding will come.
|

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.