2016-02-26 39 views
1

我正在用Functors和QuickCheck做运动。QuickChecking simple Functors:是否需要定义任意实例?为什么?怎么样?

我有一个超级简单的函数,其组成法我希望quickCheck。 该Functor只是一个Identity a。 这是我的代码至今:

import Data.Functor 
import Test.QuickCheck 

newtype Identity a = Identity a 

instance (Eq a) => Eq (Identity a) where 
    (==) (Identity x) (Identity y) = x == y 
    (/=) (Identity x) (Identity y) = x /= y 

instance Functor Identity where 
    fmap f (Identity x) = Identity (f x) 

propertyFunctorCompose ::(Eq (f c), Functor f) => (a -> b) -> (b -> c) -> f a -> Bool 
propertyFunctorCompose f g fr = (fmap (g . f) fr) == (fmap g . fmap f) fr 

main = do 
    quickCheck $ \x -> propertyFunctorCompose (+1) (*2) (x :: Identity Int) 

遗憾的是这段代码不能编译,GHC与此编译错误抱怨:

functor_exercises.hs:43:5: 
    No instance for (Arbitrary (Identity Int)) 
     arising from a use of `quickCheck' 
    Possible fix: 
     add an instance declaration for (Arbitrary (Identity Int)) 
    In the expression: quickCheck 
    In a stmt of a 'do' block: 
     quickCheck $ \ x -> propertyFunctorId (x :: Identity Int) 
    In the expression: 
     do { quickCheck $ \ x -> propertyFunctorId (x :: [Int]); 
      quickCheck 
      $ \ x -> propertyFunctorCompose (+ 1) (* 2) (x :: [Int]); 
      quickCheck (propertyFunctorCompose' :: IntFC); 
      quickCheck $ \ x -> propertyFunctorId (x :: Identity Int); 
      .... } 

所以我已经开始看快速检查任意类型类,它需要定义arbitrary :: Gen ashrink :: a -> [a]

我有(也许是错误的)感觉,我不应该为这样一个简单的函子定义任意实例。

如果我确实需要定义Identity的实例Arbitrary,那么我不知道arbitraryshrink应该是什么样子以及它们应该如何表现。

你能指导我吗?

回答

5

您确定需要该实例才能使用quickcheck。

但是,由于函子就是这么简单,这是相当简单:Identity A同构于A本身,因此它也允许完全相同的Arbitrary实例。这与您的Eq实例基本相同。

instance (Arbitrary a) => Arbitrary (Identity a) where 
    arbitrary = Identity <$> arbitrary 
    shrink (Identity v) = Identity <$> shrink v 
相关问题