从其定义之外访问 class 实例的成员

Access member of class instance from outside its definition

我有这种类型:

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

我必须为此类型创建一个幺半群实例,但为此我必须使用幺半群 a 的 mempty 和 mappend,无论它是什么。怎么做到这一点?

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

提前致谢

mempty只是amempty和传入的s

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

mappend可以定义为运行f,然后g根据f的结果,然后mappending结果:

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