Michael
Michael

Reputation: 42050

How to use Reader and Writer monads in Scala?

Suppose I am writing a program, which reads some input, processes it and writes the output.

Suppose also I have a function def process(input: MyInput): MyOutput

Now I should use a Reader monad for the input.

def readAndProcess(reader: MyReader[MyInput]): MyReader[MyOutput] = 
  for(in <- reader) yield process(in)

So far, so good but now I need to write the output somewhere. That is, I need a Writer monad and can define a function readProcessAndWrite

def readProcessAndWrite(reader: MyReader[MyInput]): MyWriter[MyOutput]

Suppose I have a function

def write(out: MyOutput, writer: MyWriter[MyOutput]) : MyWriter[MyOutput]

How can I define readProcessAndWrite ?

def readProcessAndWrite(reader: MyReader[MyInput], 
                        writer: MyWriter[MyOutput]): MyWriter[MyOutput] = ... ???

Upvotes: 2

Views: 1052

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

I think you misunderstand a bit. Reader monad isn't intended for reading input to the program, but to avoid passing the same argument to various functions. Similarly, Writer is about accumulating some state over calculations, not about writing it to (e.g.) standard output or a file. (Of course, you can write it after it's accumulated, but you wouldn't use the Writer monad for this!)

If you really want to combine them, you need either to write a combined monad (ReaderWriter[MyInput, MyOutput]; see this question) or monad transformers (ReaderT[MyInput, Writer[MyOutput]] or vice versa).

Upvotes: 5

Related Questions