我尝试解决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: ''


如何解决问题?

最佳答案

通常情况下,

import Data.Monoid hiding ((<>))


(或者根本不导入Data.Monoid –正如Alec所说,Monoid类本身已经从Prelude导出了。)
那么x <> y的含义就明确了,因为x Data.Semigroup.<> y版本不在范围之内。

或者,您可以导入合格的模块之一,例如

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

关于haskell - 指半群或Monoid,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44805103/

10-09 15:53