6

Monads define Semigroups via

instance Monad m => Semigroup (m a) where
    (<>) = (>>)

using FlexibleInstances.

If I wanted to make Maybe a into a Semigroup in that way I would run into an Intance overlap, because Data.Semigroup defines an

instance Semigroup a => Semigroup (Maybe a)

What is the Haskell-Way to resolve something like that?

1 Answer 1

11

The common way in which these problems are solved is with a newtype wrapper. You wouldn't define an instance Semigroup (m a), but rather

newtype WrappedMonad m a = WrappedMonad { getWrappedMonad :: m a }

instance Monad m => Semigroup (WrappedMonad m a) where
    WrappedMonad a <> WrappedMonad b = WrappedMonad (a >> b)
1
  • Thanks! That works like a charm. I just wish there was a way to hide the instances..
    – mr-
    Mar 27, 2013 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.