首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数据构造函数不在范围内: Monoid ::Bull -> TestBatch

数据构造函数不在范围内: Monoid ::Bull -> TestBatch
EN

Stack Overflow用户
提问于 2018-10-27 13:37:54
回答 2查看 121关注 0票数 0

Haskell的书“Haskell编程从第一原则”第1086页有一个例子来说明False不应该用作mempty of Monoid,但是这个页面上的代码没有编译,我也不知道为什么。守则如下:

代码语言:javascript
复制
module BadMonoid where

import Data.Monoid
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes

data Bull =
  Fools
  | Twoo
  deriving (Eq, Show)

instance Arbitrary Bull where
  arbitrary =
    frequency [(1, return Fools)
              ,(1, return Twoo)]

instance Monoid Bull where
  mempty = Fools
  mappend _ _ = Fools

main :: IO ()
main = do
  quickBatch (monoid Twoo)

语法检查器显示此代码的两个错误:

代码语言:javascript
复制
• No instance for (Semigroup Bull)
    arising from the superclasses of an instance declaration
• In the instance declaration for ‘Monoid Bull’

代码语言:javascript
复制
• No instance for (EqProp Bull) arising from a use of ‘monoid’
• In the first argument of ‘quickBatch’, namely ‘(monoid Twoo)’
  In a stmt of a 'do' block: quickBatch (monoid Twoo)
  In the expression: do quickBatch (monoid Twoo)

stack ghci repl中加载此文件将显示:

代码语言:javascript
复制
[1 of 1] Compiling BadMonoid        ( src/Main.hs, interpreted )

src/Main.hs:18:10: error:
    • No instance for (Semigroup Bull)
        arising from the superclasses of an instance declaration
    • In the instance declaration for ‘Monoid Bull’
   |
18 | instance Monoid Bull where
   |          ^^^^^^^^^^^

src/Main.hs:39:15: error:
    • No instance for (EqProp Bull) arising from a use of ‘monoid’
    • In the first argument of ‘quickBatch’, namely ‘(monoid Twoo)’
      In a stmt of a 'do' block: quickBatch (monoid Twoo)
      In the expression: do quickBatch (monoid Twoo)
   |
39 |   quickBatch (monoid Twoo)
   |               ^^^^^^^^^^^

你能帮我修复这段代码吗?根据这本书,实际结果应该是:

代码语言:javascript
复制
Prelude> main
monoid:
  left  identity: *** Failed! Falsifiable (after 1 test):
Twoo
  right identity: *** Failed! Falsifiable (after 2 tests):
Twoo
  associativity:  +++ OK, passed 500 tests.

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-27 13:47:59

看来Monoid的定义自从这本书写出来后就发生了变化。As 文件说明

注意:半群是从Bas-4.11.0.0开始的莫尼特的超类。

实例现在应该如下所示:

代码语言:javascript
复制
instance Monoid Bull where
  mempty = Fools

instance Semigroup Bull where
  _ <> _ = Fools

(mappend现在只需调用<>。)

对于EqProp实例,可以从Eq派生如下:

代码语言:javascript
复制
instance EqProp Bull where
  (=-=) = eq
票数 2
EN

Stack Overflow用户

发布于 2018-10-27 13:43:48

第二个错误很抱歉:

我失去了一条线

代码语言:javascript
复制
instance EqProp Bull where (=-=) = eq

第一个错误:

我加了

代码语言:javascript
复制
instance Semigroup Bull where _ <> _ = Fools

Monoid实例化上面,第一个错误消失了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53022425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档