Skip to content

Instantly share code, notes, and snippets.

@tfausak
Created April 2, 2016 13:09
Show Gist options
  • Save tfausak/d4f327d8338469bf41f202f59a814245 to your computer and use it in GitHub Desktop.
Save tfausak/d4f327d8338469bf41f202f59a814245 to your computer and use it in GitHub Desktop.
Reader monad example in Haskell.
-- https://www.stackage.org/package/transformers
import qualified Control.Monad.Trans.Reader as Reader
main :: IO ()
main = do
let result = Reader.runReader computationToRun initialValue
putStrLn result
{- Output:
There are 3 thing(s) in the environment.
x = Just "hello", y = Just "world"
-}
type Environment = [(String, String)]
initialValue :: Environment
initialValue =
[ ("key", "value")
, ("x", "hello")
, ("y", "world")
]
computationToRun :: Reader.Reader Environment String
computationToRun = do
count <- Reader.asks length
let message = "There are " ++ show count ++ " thing(s) in the environment."
rest <- nestedComputation
return (message ++ "\n" ++ rest)
nestedComputation :: Reader.Reader Environment String
nestedComputation = do
x <- Reader.asks (lookup "x")
y <- Reader.asks (lookup "y")
return ("x = " ++ show x ++ ", y = " ++ show y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment