Skip to content

Instantly share code, notes, and snippets.

@hrldcpr
Created July 28, 2014 16:23
Show Gist options
  • Save hrldcpr/5270b7e3b30a308d2810 to your computer and use it in GitHub Desktop.
Save hrldcpr/5270b7e3b30a308d2810 to your computer and use it in GitHub Desktop.
simple example of Reader monad
import qualified Data.Maybe as Maybe
import qualified Control.Monad.Reader as Reader
type Environment = [(String, String)]
get :: String -> Environment -> String
get k env = Maybe.fromJust $ lookup k env
asks :: String -> Reader.Reader Environment String
asks k = Reader.asks $ get k
name_string :: Reader.Reader Environment String
name_string = do
name <- asks "name"
return $ "Name: " ++ name
phone_string :: Reader.Reader Environment String
phone_string = do
phone <- asks "phone"
return $ "Phone: " ++ phone
business_card :: Reader.Reader Environment String
business_card = do
name <- name_string
phone <- phone_string
return $ name ++ "\n" ++ phone
card :: Environment -> String
card env = Reader.runReader business_card env
main = putStrLn $ card [("name", "Harold"), ("phone", "303.880.9599")]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment