Reputation: 139
I am having difficulty in understanding the Reader Monad. My understanding from all the places I read, is that it allows to share a variable(Read Mode) to different function. Below is the implementation of two functions computation and samething (sorry for bad function names), one with Reader and one without it. I don't get the benefit using Reader.
module Moreunderstanding where
import Control.Monad.Reader
computation :: Reader Int Int
computation = do
a <- ask
b <- asks square
return (a + b)
square :: Int -> Int
square x = x ^ 2
samething:: Int -> Int
samething = do
a <- square
b <- id
return (a + b)
I am not sure what is that I am missing here.
Upvotes: 1
Views: 419
Reputation: 1228
The Reader monad becomes more useful when you have several arguments that you have to pass around from function to function. For example if you're building some API endpoints and you want to pass a configuration object around. In that case it's much easier to use the Reader monad and keep the inner functions signature clean.
Upvotes: 2
Reputation: 54058
These do both do the same thing. In fact, the Reader monad is pretty much the same as the function monad (which you're using in samething
). It becomes useful because of the MonadReader
typeclass (which (->) a
has an instance for) and ReaderT
, which allow you to stack multiple monad transformers on top of one another.
It's also a good statement of intent. It means "I have a read-only value here that will be used in this computation". I'd say that your intuition is pretty accurate though, there isn't much to the Reader monad, it's pretty simple.
Upvotes: 4