Created
November 9, 2012 22:36
-
-
Save twopoint718/4048770 to your computer and use it in GitHub Desktop.
Using the Reader Monad
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 | |
| import Prelude hiding (last) | |
| import Text.Printf | |
| import qualified Data.Map as M | |
| type PersonInfo = Reader (M.Map String String) String | |
| gimmie :: String -> PersonInfo | |
| gimmie key = asks (M.findWithDefault "" key) | |
| formattedEmailAddress :: PersonInfo | |
| formattedEmailAddress = do | |
| name <- schoolName | |
| email <- emailPart | |
| return $ printf "\"%s\" %s" name email | |
| emailPart :: PersonInfo | |
| emailPart = do | |
| first <- gimmie "first" | |
| last <- gimmie "last" | |
| domain <- gimmie "domain" | |
| return $ printf "<%s.%s@%s>" first last domain | |
| schoolName :: PersonInfo | |
| schoolName = do | |
| last <- gimmie "last" | |
| first <- gimmie "first" | |
| return $ printf "%s, %s" last first | |
| main = putStrLn $ runReader formattedEmailAddress db | |
| where db = M.fromList [("first", "Chris") | |
| , ("last", "Wilson") | |
| , ("domain", "example.com") | |
| ] |
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 Text.Printf | |
| import Prelude hiding (last) | |
| formattedEmailAddress first last domain = printf "\"%s\" %s" name email | |
| where name = schoolName first last | |
| email = emailPart first last domain | |
| emailPart :: String -> String -> String -> String | |
| emailPart first last domain = printf "<%s.%s@%s>" first last domain | |
| schoolName :: String -> String -> String | |
| schoolName first last = printf "%s, %s" last first | |
| main = putStrLn $ formattedEmailAddress "Chris" "Wilson" "example.com" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment