Skip to content

Instantly share code, notes, and snippets.

@duangsuse
Created May 19, 2019 08:58
Show Gist options
  • Save duangsuse/01d57ca3c967d60d010c44228ba8a8b1 to your computer and use it in GitHub Desktop.
Save duangsuse/01d57ca3c967d60d010c44228ba8a8b1 to your computer and use it in GitHub Desktop.
Stupid Reader Monad Instance
{-# LANGUAGE ApplicativeDo #-}
newtype Reader t a = Reader { runReader :: t -> a }
instance Functor (Reader t) where
fmap f (Reader g) = Reader (\x -> f (g x))
instance Applicative (Reader t) where
pure = return
Reader f <*> Reader g = Reader $ \x -> (f x) (g x)
instance Monad (Reader t) where
return x = Reader (\_ -> x)
Reader f >>= g = Reader (\x -> runReader (roll x) x)
where roll = g . f
ask :: (t -> a) -> Reader t a
ask f = Reader (\x -> f x)
data Enviroment = Env { name :: String, price :: String, desc :: String }
deriving (Eq, Show)
dogeR :: Reader Enviroment String
dogeR = do
n <- ask name
p <- ask price
d <- ask desc
return (n ++ ": $" ++ p ++ "\n" ++ d)
doge :: String
doge = runReader dogeR (Env "World" "50000" "Beautiful world!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment