为使用Maybe

时间:2016-10-17 15:02:00

标签: haskell quickcheck

我想为以下newtype创建一个Arbitrary实例,以便将其用于QuickCheck:

newtype Wrapmaybe a = Wrapmaybe {getMaybe :: Maybe a} deriving (Eq, Show)

我知道Arbitrary的{​​{1}}实例可以写成如下:

Maybe

如何在不出现类型错误或类型错误的情况下为instance Arbitrary a => Arbitrary (Maybe a) where arbitrary = frequency [(1, return Nothing), (1, liftM Just arbitrary)] 实例编写以下内容:

Arbitrary

1 个答案:

答案 0 :(得分:10)

好吧,您可以使用相应的newtype构造函数替换该实例中的每个Maybe构造函数:

instance Arbitrary a => Arbitrary (WrapMaybe a) where
  arbitrary = frequency [ (1, return $ WrapMaybe Nothing)
                        , (1, fmap (WrapMaybe . Just) arbitrary) ]

但是,使用现有的Maybe实例对结果执行一次更简单:

instance Arbitrary a => Arbitrary (WrapMaybe a) where
  arbitrary = fmap WrapMaybe arbitrary

您也可以写WrapMaybe <$> arbitrary。但请使用liftM,即obsolete! (这些都是等价的。)