我尝试从haskellbook解决练习并创建以下模块:
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
编译器抱怨:
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: ''
如何解决问题?
答案 0 :(得分:5)
通常,你只是
import Data.Monoid hiding ((<>))
(或者根本就没有导入Data.Monoid
- 正如Alec评论的那样,Monoid
类本身已经从Prelude
导出了。)
然后明确x <> y
表示x Data.Semigroup.<> y
,因为Data.Monoid
版本不在范围内。
或者,您可以导入其中一个合格的模块,例如
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