{-- A dummy monad transformer DB for database state management whose functionality has been lifted to class Db. --} module Db ( Db, db, DB, dbExampleOp ) where import Io import STM import MonadT -- a class for monads composed from DB: class Monad m => Db m where db :: DBImpl m -- monad transformer DB: newtype DB m a = DB (STM DBStat m a) fromDB (DB a) = a toDB = DB instance Monad m => Functor (DB m) where fmap f = toDB . fmap f . fromDB instance Monad m => Monad (DB m) where m >>= f = toDB ((fromDB m) >>= (fromDB . f)) return = toDB . return instance MonadT DB where lift = toDB . lift start = run "" . fromDB -- lift IO functionality to DB: instance Io m => Io (DB m) where io = lift . io instance Monad m => Db (DB m) where db = DBImpl (toDB . modify) -- state (represented by a string in this example): type DBStat = String -- ADT that encapsulates the specific operations of the DB monad: data DBImpl m = DBImpl ((DBStat -> DBStat) -> m DBStat) instance Liftable DBImpl where mapLift (DBImpl m) = DBImpl (lift . m) -- some example DB operation: set state & read it & print: dbExampleOp :: (Io m, Db m) => String -> m () dbExampleOp str = do modify (\_ -> str) result <- modify id putStrC result where (DBImpl modify) = db