我想为以下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
答案 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! (这些都是等价的。)