QuickChecking简单的Functors:定义一个必要的Arbitrary实例吗?为什么?怎么样?

时间:2016-02-26 00:22:38

标签: haskell functor quickcheck

我正在使用Functors和QuickCheck进行锻炼。

我有一个超级简单的Functor,其组成法我想快速检查。 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);
           .... }

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

我有(可能是假的)感觉,我不需要为这样一个简单的仿函数定义Arbitrary实例。

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

你可以指导我吗?

1 个答案:

答案 0 :(得分:5)

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

但是,因为这个仿函数非常简单,所以非常简单:Identity AA本身是同构的,所以它也允许完全相同Arbitrary实例。这与您的Eq实例基本相同。

instance (Arbitrary a) => Arbitrary (Identity a) where
    arbitrary = Identity <$> arbitrary
    shrink (Identity v) = Identity <$> shrink v