【发布时间】:2018-09-10 23:58:59
【问题描述】:
对于 Haskell Programming From First Principles 第 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.
那么我在这里做错了吗?为什么我不能在这里使用现有数据的 typeclass 作为约束?
【问题讨论】:
标签: haskell polymorphism typeclass parametric-polymorphism