I am trying to understand when to use the reader monad, but I haven’t found a good usage example. I am pretty sure I have limited knowledge on this topic.
Consider this example code:
import Control.Monad.Reader
data Env = Env
{ eInt :: Int
, eStr :: String
}
calculateR :: Reader Env Int
calculateR = do
e <- ask
return $ eInt e
calculate :: Env -> Int
calculate = eInt
main :: IO ()
main = do
let env = Env { eInt = 1, eStr = "hello"}
let a = runReader calculateR env
let b = calculate env
print (a,b)
If I want to pass around the global Env to be able to access it from any function, should I use the reader monad for this purpose?
In comparison to just passing the Env directly to the function, is there any benefit?
If I understand correctly, both calculate and calculateR are pure (in the sense that they won't be able to make any change to env), and both have Env in their type signature telling that they might read the value form env to use in their computation.
calculateR = asks eIntorcalculateR = eInt <$> askto reduce the syntactic overhead