-- Sample solution -- suppress warnings about old-style Monad definitions {-# OPTIONS_GHC -Wno-noncanonical-monad-instances #-} module RWSP where import Control.Monad -- The class of monads that support the core RWS operations class Monad rws => RWSMonad rws where ask :: rws ReadData with :: ReadData -> rws a -> rws a tell :: WriteData -> rws () get :: rws StateData put :: StateData -> rws () -- We want to build a monad that supports this: -- RWSP is an RWS monad instance RWSMonad RWSP where ask = askP; with = withP; tell = tellP; get = getP; put = putP type ReadData = Int -- Future perhaps an AST type WriteData = String -- must be an instance of Monoid type StateData = Double -- Future perhaps an dictionary -- A Monoid is a "semigroup" with an append, and in addition an empty funtion. -- Plain version of RWS monad newtype RWSP a = RWSP {runRWSP :: ReadData -> StateData -> (a, WriteData, StateData)} instance Monad RWSP where -- return :: a -> RWSP a return a = RWSP (\_r s -> (a, mempty, s) ) -- (>>=) :: RWSP a -> (a -> RWSP b) -> RWSP b m >>= f = RWSP (\r s -> let (a1, w1, s1) = runRWSP m r s (a2, w2, s2) = runRWSP (f a1) r s1 in (a2, w1 <> w2, s2)) -- No need to touch these instance Functor RWSP where fmap = liftM instance Applicative RWSP where pure = return; (<*>) = ap -- returns current read data askP :: RWSP ReadData askP = RWSP (\r s -> (r, mempty, s)) -- runs computation with new read data withP :: ReadData -> RWSP a -> RWSP a withP r' m = RWSP (\_r s -> runRWSP m r' s) -- adds some write data to accumulator tellP :: WriteData -> RWSP () tellP w = RWSP (\_r s -> ((), w, s)) -- returns current state data getP :: RWSP StateData getP = RWSP (\r s -> (s, mempty, s)) -- overwrites the state data putP :: StateData -> RWSP () putP s' = RWSP (\_r _s -> ((), mempty, s')) -- sample computation using all features type Answer = String type Result = (Answer, WriteData, StateData) sampleP :: RWSP An swer sampleP = do tell "Hello" r1 <- askP r2 <- withP 5 askP tell " World" s1 <- getP putP (s1 + 1.0) tell "State update" return $ "r1:" ++ show r1 ++ " r2: " ++ show r2 sampleP' :: RWSP Answer sampleP' = (ask) >>= (\x -> return $ show x) runP = runRWSP sampleP 4 3.5 runP' = runRWSP sampleP' 4 3.5