Created
March 16, 2014 09:53
-
-
Save tuttlem/9580902 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
import Control.Monad.Reader | |
-- | Shared configuration for this application. | |
-- Rather trivial (and useless), it just configures how our application will | |
-- address the user | |
-- | |
data SalutationConfig = SalutationConfig { formal :: Bool } | |
-- | Returns a greeting | |
-- Takes in someone's name and returns a greeting string | |
-- | |
greeter :: String -> Reader SalutationConfig String | |
greeter name = do | |
-- grab the configuration out | |
cfg <- ask | |
-- grab the "formal" setting from the config | |
let f = formal cfg | |
-- send out the value | |
return (makeSalutation f ++ name) | |
-- | Makes a salutation for a "formal" setting | |
makeSalutation :: Bool -> String | |
makeSalutation True = "Good day, " | |
makeSalutation False = "Wasaaaaaaaap, " | |
main :: IO () | |
main = do | |
-- create the configuration | |
let cfg = SalutationConfig { formal = False} | |
-- run the reader with the configuration for a guy named "Michael" | |
let msg = runReader (greeter "Michael") $ cfg | |
-- "Wasaaaaaaaaaap, Michael" | |
putStrLn msg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment