对于 Haskell编程从第一原理的第15章中的练习,我试图基于另一个Arbitrary
实例编写一个Arbitrary
实例:
module AccumulateRight where
import Data.Semigroup
import Test.QuickCheck
data Validation a b = Fail a | Pass b deriving (Eq, Show)
newtype AccumulateRight a b =
AccumulateRight (Validation a b) deriving (Eq, Show)
type TestType = AccumulateRight String [Int]
instance Semigroup b => Semigroup (AccumulateRight a b) where
_ <> (AccumulateRight (Fail x)) = Fail x
(AccumulateRight (Fail x)) <> _ = Fail x
(AccumulateRight (Success a)) <> (AccumulateRight (Success b)) =
AccumulateRight . Success $ a <> b
instance (Arbitrary a, Arbitrary b) => Arbitrary (Validation a b) where
arbitrary = oneof [Fail <$> arbitrary, Pass <$> arbitrary]
instance Arbitrary (Validation a b) => Arbitrary (AccumulateRight a b) where
arbitrary = AccumulateRight <$> arbitrary
semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c)
type Assoc = TestType -> TestType -> TestType -> Bool
main :: IO ()
main = quickCheck (semigroupAssoc :: Assoc)
但发生以下错误:
• Non type-variable argument
in the constraint: Arbitrary (Validation a b)
(Use FlexibleContexts to permit this)
• In the context: Arbitrary (Validation a b)
While checking an instance declaration
In the instance declaration for ‘Arbitrary (AccumulateRight a b)’
|
22 | instance Arbitrary (Validation a b) => Arbitrary (AccumulateRight a b) where
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.
那么我在这里做错什么了吗?为什么在这里我不能使用现有数据的类型类作为约束?
答案 0 :(得分:4)
这是一个愚蠢的限制,在人们理解类型类实现起来有多困难之前,就施加了这种限制。事实证明,它很容易支持,因此有一个语言扩展(错误中提到),您可以这样说。您可以通过添加
打开它{-# LANGUAGE FlexibleContexts #-}
文件的顶部,随着扩展名的增加,该扩展名被认为是完全良性的。但是,在这种情况下,您不应该打开它,而应该只写
instance (Arbitrary a, Arbitrary b) => Arbitrary (AccumulateRight a b)
-毕竟(Arbitrary a, Arbitrary b)
正是Arbitrary (Validation a b)
成立的条件。