Created
June 13, 2012 13:44
-
-
Save chris-taylor/2924160 to your computer and use it in GitHub Desktop.
Reader monad example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Module1 where | |
import Control.Monad.Reader | |
data Config = Config { arg :: Int } | |
initialize :: IO Config | |
initialize = do | |
n <- getLine | |
return $ Config (read n) | |
function1 :: Reader Config Int | |
function1 = do | |
conf <- ask | |
return (arg conf + 1) | |
function2 :: Reader Config Int | |
function2 = do | |
conf <- ask | |
return (arg conf + 2) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Module2 where | |
import Module1 | |
import Control.Monad.Reader | |
main = do | |
conf <- initialize | |
let n1 = runReader function1 conf | |
let n2 = runReader function2 conf | |
putStrLn $ "Results: " ++ show (n1,n2) |
NB I totally have not type checked any of the above!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You probably want to use the
>>=
operator to chain your functions. Let me see if I can whip up an example.So you have some config
and some functions that use it
and you want to chain them together without having to manually pass the config to each function like this
using a reader lets you define your functions as
which looks like a lot more work, but now you can chain them together like
and run the whole thing with
Is that what you're after?