Skip to content

Instantly share code, notes, and snippets.

@louy2 louy2/reader.hs
Last active Feb 24, 2019

Embed
What would you like to do?
Reader Monad practice
{-# LANGUAGE InstanceSigs #-}
newtype Reader e a = Reader (e -> a)
runReader :: Reader e a -> e -> a
runReader (Reader f) = f
instance Functor (Reader e) where
fmap :: (a -> b) -> Reader e a -> Reader e b
fmap a2b (Reader e2a) = Reader (a2b . e2a)
instance Applicative (Reader e) where
pure :: a -> Reader e a
pure = Reader . const
(<*>) :: Reader e (a -> b) -> Reader e a -> Reader e b
(<*>) (Reader e2a2b) (Reader e2a) = let e2b e = e2a2b e (e2a e) in Reader e2b
instance Monad (Reader e) where
(>>=) :: Reader e a -> (a -> Reader e b) -> Reader e b
(>>=) (Reader e2a) a2reb = let e2b e = runReader (a2reb (e2a e)) e in Reader e2b
reader :: (e -> a) -> Reader e a
reader = Reader
ask :: Reader e e
ask = Reader id
local :: (e -> e) -> Reader e a -> Reader e a
local f (Reader e2a) = Reader (e2a . f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.