Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created November 23, 2016 08:53
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 naoto-ogawa/4d6a04b16cd206a7e439073f6833d29c to your computer and use it in GitHub Desktop.
Save naoto-ogawa/4d6a04b16cd206a7e439073f6833d29c to your computer and use it in GitHub Desktop.
Grokking Reader Monad without implementation
import Control.Monad.Reader
-- ========================================= --
-- a base case (just for comparison)
-- ========================================= --
doJob1 :: () -> String
doJob2 :: String -> Int
doJob3 :: Int -> [String]
doJob1 = undefined
doJob2 = undefined
doJob3 = undefined
doJob12 = doJob2 . doJob1
doJob123 = doJob3 . doJob2 . doJob1
-- > :t doJob12
-- doJob12 :: () -> Int
-- > :t doJob123
-- doJob123 :: () -> [String]
-- ========================================= --
-- Use a configuration
-- ========================================= --
data Conf = Conf [(Char, Int)]
doJob1' :: Conf -> () -> String
doJob2' :: Conf -> String -> Int
doJob3' :: Conf -> Int -> [String]
doJob1' = undefined
doJob2' = undefined
doJob3' = undefined
-- doJob12' = ??
-- doJob123' = ??
doJob12' = \x -> doJob2' x $ doJob1' x ()
doJob123' = \x -> doJob3' x $ doJob2' x $ doJob1' x ()
-- > :t doJob12'
-- doJob12' :: Conf -> Int
-- > :t doJob123'
-- doJob123' :: Conf -> [String]
-- ========================================= --
-- Make use of Reader Monad
-- ========================================= --
doJobR1 :: () -> Reader Conf String
doJobR2 :: String -> Reader Conf Int
doJobR3 :: Int -> Reader Conf [String]
doJobR1 = undefined
doJobR2 = undefined
doJobR3 = undefined
doJobR12 = doJobR1 () >>= doJobR2
doJobR123 = doJobR1 () >>= doJobR2 >>= doJobR3
-- > :t doJobR12
-- doJobR12 :: ReaderT Conf Data.Functor.Identity.Identity Int
-- > :t runReader doJobR12
-- runReader doJobR12 :: Conf -> Int
-- > :t doJobR123
-- doJobR123 :: ReaderT Conf Data.Functor.Identity.Identity [String]
-- > :t runReader doJobR123
-- runReader doJobR123 :: Conf -> [String]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment