Snippets

Brian McKenna gndog: Untitled snippet

Created by Brian McKenna
{-# LANGUAGE FlexibleContexts #-}

import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.State
import Prelude hiding (print)
import qualified Prelude as P

print :: (MonadIO m, Show a) => a -> m ()
print = liftIO . P.print

newtype MyConfig = MyConfig String deriving Show

newtype MyState = MyState Int deriving Show

getData :: (MonadIO m, MonadReader MyConfig m) => m Int
getData = do
  MyConfig config <- ask
  print config
  return $ length config

getMoreData :: (MonadReader MyConfig m, MonadState MyState m) => Int -> m Int
getMoreData x = do
  MyConfig name <- ask
  MyState origState <- get
  put (MyState $ origState + x + length name)
  return origState

getEvenMoreData :: (MonadIO m, MonadState MyState m) => Int -> Int -> m Int
getEvenMoreData x y = do
  print x
  print y
  MyState total <- get
  return total

program :: (MonadIO m, MonadReader MyConfig m, MonadState MyState m) => m ()
program = do
  a <- getData
  b <- getMoreData a
  c <- getMoreData b
  d <- getEvenMoreData a c
  print d

runProd :: (Monad m) => ReaderT MyConfig (StateT MyState m) a -> m a
runProd = flip evalStateT (MyState 0) . flip runReaderT (MyConfig "production-config")

main :: IO ()
main = runProd program

Comments (0)