Skip to content

Instantly share code, notes, and snippets.

@hrldcpr
Last active August 29, 2015 14:04
Show Gist options
  • Save hrldcpr/0b4b9e558f119b2cf7fa to your computer and use it in GitHub Desktop.
Save hrldcpr/0b4b9e558f119b2cf7fa to your computer and use it in GitHub Desktop.
combination of Reader and Maybe monads, using the ReaderT monad transformer
import Control.Monad.Reader
import Control.Monad.Trans
import Data.List
import Data.Maybe
import Text.Printf
type Environment = [(String, String)]
get :: String -> ReaderT Environment Maybe String
get k = ask >>= lift . lookup k
-- here's the do-notation equivalent:
get' :: String -> ReaderT Environment Maybe String
get' k = do
env <- ask
lift $ lookup k env
format :: String -> String -> ReaderT Environment Maybe String
format fmt k = get k >>= return . printf fmt
business_card_lines :: Reader Environment [String]
business_card_lines = do
let lines = [format "Name: %s" "name",
format "Email: %s" "email",
format "Phone: %s" "phone"]
env <- ask
return $ catMaybes $ map (\r -> runReaderT r env) lines
business_card :: Reader Environment String
business_card = business_card_lines >>= return . intercalate "\n"
main = putStrLn $ runReader business_card [("name", "Harold"), ("email", "hrldcpr@gmail.com")]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment