Skip to content

Instantly share code, notes, and snippets.

@tuttlem
Created March 16, 2014 09:53
Show Gist options
  • Save tuttlem/9580902 to your computer and use it in GitHub Desktop.
Save tuttlem/9580902 to your computer and use it in GitHub Desktop.
Reader monad example
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