Monad instance for pairs

后端 未结 2 2050
傲寒
傲寒 2021-01-23 20:55

This question shows an instance definition for (,) a b, where a is an instance of Monoid.

However, I don\'t know how to write sim

相关标签:
2条回答
  • 2021-01-23 21:46

    We could write, for now synonyms works inappropriate for this case, so we use newtype:

    newtype RevTuple b a = RevTuple { totuple :: (a , b) }
    
    instance Monoid b => Monad (RevTuple b) where
        return a = RevTuple (a,mempty)
        (RevTuple (a,b)) >>= f = 
                     let RevTuple (c,b1) = f a in RevTuple (c,b `mappend` b1)
    
    0 讨论(0)
  • 2021-01-23 21:53

    You cannot. It's crucial for Monad to be polymorphic in its parameter, so if a particular monadish thing only makes sense for monoids, it's not a monad.

    For example, return :: Monad m => a -> m a. There's no way you can add an extra constraint to the signature of return.

    0 讨论(0)
提交回复
热议问题