Haskell的书“Haskell编程从第一原则”第1086页有一个例子来说明False不应该用作mempty of Monoid,但是这个页面上的代码没有编译,我也不知道为什么。守则如下:
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)语法检查器显示此代码的两个错误:
• No instance for (Semigroup Bull)
arising from the superclasses of an instance declaration
• In the instance declaration for ‘Monoid Bull’和
• 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中加载此文件将显示:
[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)
| ^^^^^^^^^^^你能帮我修复这段代码吗?根据这本书,实际结果应该是:
Prelude> main
monoid:
left identity: *** Failed! Falsifiable (after 1 test):
Twoo
right identity: *** Failed! Falsifiable (after 2 tests):
Twoo
associativity: +++ OK, passed 500 tests.谢谢!
发布于 2018-10-27 13:47:59
看来Monoid的定义自从这本书写出来后就发生了变化。As 文件说明
注意::半群是从Bas-4.11.0.0开始的莫尼特的超类。
实例现在应该如下所示:
instance Monoid Bull where
mempty = Fools
instance Semigroup Bull where
_ <> _ = Fools(mappend现在只需调用<>。)
对于EqProp实例,可以从Eq派生如下:
instance EqProp Bull where
(=-=) = eq发布于 2018-10-27 13:43:48
第二个错误很抱歉:
我失去了一条线
instance EqProp Bull where (=-=) = eq第一个错误:
我加了
instance Semigroup Bull where _ <> _ = Fools在Monoid实例化上面,第一个错误消失了。
https://stackoverflow.com/questions/53022425
复制相似问题