Access member of class instance from outside its definition

94 views Asked by At

I have this type:

newtype Mem s a = Mem { runMem :: s -> (a,s) }

and I have to create an instance of monoid for this type, but to do so I have to use the mempty and the mappend of the monoid a, regardless of what it may be. How would one go about doing that?

instance Monoid a => Monoid (Mem s a) where
    mempty =  --runMem with the mempty of a
    f@(Mem aa) `mappend` g@(Mem aaa) = --runMem with mappend of a
    f@(Mem s) `mappend` mempty = f
    mempty `mappend` g@(Mem ss) = g

Thanks in advance

1

There are 1 answers

0
Chad Gilbert On BEST ANSWER

mempty is simply the mempty of a and the s that was passed in.

mempty = Mem (\s -> (mempty, s))

mappend can be defined as running f, then g based on the results of f, then mappending the results:

f `mappend` g = Mem (\s -> 
                    let (fa, fs) = runMem f s
                        (ga, gs) = runMem g fs
                    in (fa `mappend` ga, gs))