I am trying to define instances for Applicative and Monad of RWS, but there must be something that I am missing. For pure
, I am getting an occurs check error. It must have something to do with the fact that I give RWS f
as the result of pure, despite f having the type a
. I don't understand how to access the other arguments of RWS
(r, w and s). I would appreciate it if someone explained some of the notions in detail, such as the newtype
definition. As I understand it, we define a new type RWS
which has 4 arguments (r, w, s and a). This type is defined using a constructor (fromRWS
), that does something with the arguments. Correct me if I am wrong. If this is correct, is RWS
defined by the 4 arguments or by fromRWS
?
Moving further, the implementation for <*>
produces a type error. It says that fromRWS2 is applied to too few arguments. I don't see the issue, though, since I have used the same where
clause approach to solve a similar problem for a variable environment. What alternatives do can I use?
When defining Monad
, I just got a parse error on input RWS
Please help me define the instances.
Here is my code:
module RWS where
newtype RWS r w s a = RWS { fromRWS :: r -> s -> (a, s, w) }
instance Functor (RWS r w s) where
fmap f (RWS rws) = RWS $ \r s -> let (a,s',w) = rws r s in (f a, s', w)
instance Monoid w => Applicative (RWS r w s) where
-- pure a -> RWS r w s a
pure f = RWS f
-- (<*>) :: RWS r w s (a -> b) -> RWS r w s a -> RWS r w s b
RWS f <*> RWS a = RWS fromRWS2
where fromRWS2 r1 s1 = f a
instance Monoid w => Monad (RWS r w s) where
--return :: a -> RWS r w s a
return x = RWS x
--(>>=) :: (RWS r w s a) -> (a -> (RWS r w s b)) -> (RWS r w s b)
RWS fr >>= f = f fr