Access member of class instance from outside its definition


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

Show source
| haskell   | typeclass   | monoids   2017-01-05 18:01 1 Answers

Answers ( 1 )

  1. 2017-01-05 18:01

    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))
◀ Go back