Created
April 2, 2016 13:09
-
-
Save tfausak/d4f327d8338469bf41f202f59a814245 to your computer and use it in GitHub Desktop.
Reader monad example in Haskell.
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
-- 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