data Reader e a = Reader (e -> a)
instance Functor (Reader e) where
-- fmap :: (a -> b) -> Reader e a -> Reader e b
fmap f (Reader g) = Reader (f.g)
instance Applicative (Reader e) where
-- pure :: a -> Reader e a
pure x = Reader (\e -> x)
-- (<*>) :: Reader e (a -> b) -> Reader e a -> Reader e b
rab <*> ra = Reader (\e -> let fab = runReader rab e
fa = runReader ra e
in fab fa)
instance Monad (Reader e) where
-- (>>=) :: Reader e a -> (a -> Reader e b) -> Reader e b
ra >>= arb =
Reader (\e -> let a = runReader ra e -- a
rb = arb a -- Reader e b
in runReader rb e)
runReader :: Reader e a -> e -> a
runReader (Reader f) e = f e
ask :: Reader e e
ask = (Reader id)
askfor f = fmap f ask
data Config = Conf { tweet_key :: String
, api_secret :: String
}
postTweet :: String -> Reader Config String
postTweet t = do
b <- valida t
if b then return t
else return "senha inválida"
valida :: String -> Reader Config Bool
valida x = do
key <- askfor tweet_key
if key == "teste"
then return True
else return False
main = do let conf1 = Conf "teste" "senha"
conf2 = Conf "erro" "senha"
reader = postTweet "Meu tweet"
putStrLn $ runReader reader conf1
putStrLn $ runReader reader conf2