2
votes

I try to solve the exercises from the haskellbook and created following module:

module Exercises where

import Data.Semigroup
import Data.Monoid
import Test.QuickCheck

data Trivial = Trivial deriving (Eq, Show)

instance Semigroup Trivial where
  _ <> _ = Trivial

instance Monoid Trivial where
  mempty = Trivial
  mappend x y = x <> y   

And the compiler complains:

file: 'file:///d%3A/haskell/chapter15/src/Exercises.hs'
severity: 'Error'
message: 'Ambiguous occurrence `<>'
It could refer to either `Data.Semigroup.<>',
                         imported from `Data.Semigroup' at src\Exercises.hs:3:1-21
                      or `Data.Monoid.<>',
                         imported from `Data.Monoid' at src\Exercises.hs:4:1-18'
at: '14,19'
source: ''

How to solve the problem?

1
Would mappend x y = Data.Monoid.<> x y work?9000
Do you even need Data.Monoid imported? All it really brings into scope that isn't already in the Prelude is a bunch of newtypes and its version of <>.Alec
Note that this annoying situation is temporary. In GHC 8.4 or 8.6 (don't remember which), Semigroup will be a superclass of Monoid.dfeuer

1 Answers

5
votes

Normally, you'd just

import Data.Monoid hiding ((<>))

(Or simply not import Data.Monoid at all – as Alec commented, the Monoid class itself is already exported from Prelude anyway.) Then it's unambiguous that x <> y means x Data.Semigroup.<> y, because the Data.Monoid version is not in scope.

Alternatively, you can import one of the modules qualified, like

import qualified Data.Semigroup as SG
import Data.Monoid
import Test.QuickCheck

data Trivial = Trivial deriving (Eq, Show)

instance SG.Semigroup Trivial where
  _ <> _ = Trivial

instance Monoid Trivial where
  mempty = Trivial
  mappend x y = x SG.<> y