Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlapping instances by turning Monads into Semigroups

Tags:

haskell

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?

like image 403
mr- Avatar asked Mar 27 '13 12:03

mr-


1 Answers

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)
like image 115
Twan van Laarhoven Avatar answered Sep 20 '22 17:09

Twan van Laarhoven