gpt4 book ai didi

haskell - 测试和应用

转载 作者:行者123 更新时间:2023-12-04 23:14:47 25 4
gpt4 key购买 nike

我想在自定义类型上测试应用实例:

module SumMonad where

import Test.QuickCheck (Arbitrary, arbitrary, elements, Gen)
import Test.QuickCheck.Checkers (quickBatch, eq, (=-=), EqProp)
import Test.QuickCheck.Classes (applicative)

data Sum a b =
First a
| Second b
deriving (Eq, Show)

instance Functor (Sum a) where
fmap _ (First x) = First x
fmap f (Second y) = Second (f y)

instance Applicative (Sum a) where
pure = Second
First x <*> _ = First x
_ <*> First x = First x
Second f <*> Second x = Second (f x)

instance Arbitrary a => Arbitrary (Sum a b) where
arbitrary = do
a <- arbitrary
b <- arbitrary
return ???(What should I write here)

instance (Eq a, Eq b) => EqProp (Sum a b) where (=-=) = eq

如您所见,三个问号突出显示,我不知道那里有什么?

最佳答案

您需要在 First 之间随机选择和 Second ,然后生成合适的第一/第二分量。

使用 oneOf 可以快速完成有限数量的选择之间的选择。 .

 instance (Arbitrary a, Arbitrary b) => Arbitrary (Sum a b) where
arbitrary = oneOf [ First <$> arbitrary, Second <$> arbitrary ]

以上等价于以下较低级别的实例,您一开始可能会觉得更容易理解。
 instance (Arbitrary a, Arbitrary b) => Arbitrary (Sum a b) where
arbitrary = do
which <- arbitrary -- a random Bool
if which
then do
a <- arbitrary
return (First a)
else do
b <- arbitrary
return (Second b)

关于haskell - 测试和应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com