Skip to content

Instantly share code, notes, and snippets.

@MichaelXavier
Created June 26, 2014 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelXavier/0351a04ede87403f7fcf to your computer and use it in GitHub Desktop.
Save MichaelXavier/0351a04ede87403f7fcf to your computer and use it in GitHub Desktop.
Age in context
{-# 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