【问题标题】:QuickCheck limit to only certain data constructorQuickCheck 仅限于某些数据构造函数
【发布时间】:2019-12-14 17:11:51
【问题描述】:

我有一个数据类型定义:

data Point = Point {x :: Int, h :: Int} | EmptyPoint

在我的属性测试中,我想将测试限制在 Point 构造函数案例上。例如 point1 - point2 = Point 0 0。这假定访问器 x 已定义,而 EmptyPoint 不是这种情况。

换句话说:我不希望生成 EmptyPoint。

有没有办法做到这一点?

【问题讨论】:

  • 我不确定你的问题是你想限制对象的生成,或者如果你想添加一个“getter”x EmptyPoint.
  • @WillemVanOnsem 我想 quickcheck 会为 Point 类型生成随机数据。我想要的是它不会生成 EmptyPoint
  • 你需要将Point 设为Arbitrary 的一个实例。所以这意味着你可以指定如何生成任意的Points,这正是你想要的。

标签: haskell


【解决方案1】:

除了自动为您的类型派生Arbitrary 类(我假设您目前正在这样做),您可以手动编写一个并使其生成您想要的点,例如:

instance Arbitrary Point where
    arbitrary = Point <$> arbitrary <*> arbitrary

如果您愿意,也可以用更详细的方式:

instance Arbitrary Point where
    arbitrary = do
        x <- arbitrary
        y <- arbitrary
        pure Point { x, y }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多