Created
June 26, 2014 00:43
-
-
Save MichaelXavier/0351a04ede87403f7fcf to your computer and use it in GitHub Desktop.
Age in context
This file contains 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
{-# LANGUAGE FlexibleContexts #-} | |
module Main (main) where | |
import Control.Monad.Reader | |
type Year = Int | |
-- a person record has a birth year | |
data Person = Person { birthYear :: Year } | |
-- what we're saying here is that this function executes in a context | |
-- that contains the current year. This seems like overkill but you | |
-- could imagine a situation where you have lots of bits of context in | |
-- a larger program. You can focus a call to age just on the important | |
-- bit of context floating around, the current year. This function | |
-- *cannot* know about any other context | |
age :: MonadReader Year m => Person -> m Int | |
age person = do | |
now <- ask | |
return $ now - birthYear person | |
-- made up function, replace with one that gets the clock from the real world | |
getSystemYear :: IO Year | |
getSystemYear = return 2014 | |
main :: IO () | |
main = do | |
let person = Person 1988 | |
putStrLn "real talk" | |
realContext <- getSystemYear | |
let testContext = 2000 | |
let realAge = runReader (age person) realContext | |
let testAge = runReader (age person) testContext | |
print realAge | |
putStrLn "but in test" | |
print testAge | |
-- runhaskell age.hs | |
-- real talk | |
-- 26 | |
-- but in test | |
-- 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment