Monoid 类型 class

The Monoid type class

我正在尝试使用此页面 Haskell 中的幺半群:https://en.wikibooks.org/wiki/Haskell/Monoids。我在终端输入了以下信息(导入后Data.Monoid):

class Monoid a where
    mempty  :: a
    mappend :: a -> a -> a
    mconcat :: [a] -> a
    mconcat = foldr mappend memptyhere
newtype Sum a = Sum { getSum :: a }
instance Num a => Monoid (Sum a) where
     mempty = Sum 0
     Sum x `mappend` Sum y = Sum (x + y)

但是,当我尝试 Sum 5 <> Sum 6 <> Sum 10 时,我收到以下消息:

<interactive>:115:1: error:
• Non type-variable argument in the constraint: Semigroup (Sum a)
  (Use FlexibleContexts to permit this)
• When checking the inferred type
    it :: forall a. (Semigroup (Sum a), Num a) => Sum a

我不明白这些是什么错误,以及为什么 Sum 5 <> Sum 6 <> Sum 10 不起作用。

问题是您正在使用自己的 Sum 类型和 Monoid 类型 class,运算符 <>not 与您的 mappend 版本具有相同的功能。如果您要在多行 GHCi 提示符下输入此程序:

> :{
Prelude| ...paste your program in here...
Prelude| :}
>

然后试试这个:

> Sum 5 `mappend` Sum 6 `mappend` Sum 7
Sum 5 `mappend` Sum 6 `mappend` Sum 7 :: Num a => Sum a

不会有错误。如果您在 Sum 类型中添加 deriving (Show),您甚至会得到您正在寻找的答案!

Ok, modules loaded: none.
λ> :{
Prelude| class Monoid a where
Prelude|     mempty  :: a
Prelude|     mappend :: a -> a -> a
Prelude|     mconcat :: [a] -> a
Prelude|     mconcat = foldr mappend mempty
Prelude| newtype Sum a = Sum { getSum :: a } deriving (Show)
Prelude| instance Num a => Monoid (Sum a) where
Prelude|      mempty = Sum 0
Prelude|      Sum x `mappend` Sum y = Sum (x + y)
Prelude| :}
λ> Sum 5 `mappend` Sum 6 `mappend` Sum 7
Sum {getSum = 18}
λ> 

GHCi 中覆盖库定义的规则可能有点复杂,因此最好将其放入 xxx.hs 文件并使用 :l xxx.hs 将其加载到 GHCi 中进行测试.如果您尝试将此程序作为 xxx.hs 文件加载,您会得到关于该问题的更清晰的消息:

MonoidExample2.hs:7:19-24: error:
    Ambiguous occurrence ‘Monoid’
    It could refer to
       either ‘Prelude.Monoid’,
              imported from ‘Prelude’ at MonoidExample2.hs:1:1
              (and originally defined in ‘GHC.Base’)
           or ‘Main.Monoid’, defined at MonoidExample2.hs:1:1

然后,您可以使用特殊的 import Prelude 语法来隐藏您不需要的库定义。以下版本作为独立程序运行:

import Prelude hiding (Monoid, mempty, mappend, mconcat, (<>))

class Monoid a where
  mempty  :: a
  mappend :: a -> a -> a
  mconcat :: [a] -> a
  mconcat = foldr mappend mempty

newtype Sum a = Sum { getSum :: a } deriving (Show)

instance Num a => Monoid (Sum a) where
  mempty = Sum 0
  Sum x `mappend` Sum y = Sum (x + y)

(<>) :: Monoid a => a -> a -> a
(<>) = mappend

main :: IO ()
main = print $ Sum 5 <> Sum 6 <> Sum 10