如何在Quickcheck中使用修饰符(在我的情况下为正数) [英] How to use modifiers with Quickcheck (Positive in my case)

查看:123
本文介绍了如何在Quickcheck中使用修饰符(在我的情况下为正数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数, rev ,它为三个类型类型中的类型返回一些值:

I've a function, rev, that returns some value for a type that is in three typeclasses:

rev :: (Integral a, Show a, Read a) => a -> a
rev = read . reverse . show

我想用quickcheck测试一些关于它的属性。虽然我对测试Integral类型的负值不感兴趣,因为我使用 Integer 缺少 Natural 输入基础库。所以我想,让我们看看生成的值为负值时的相反值,我会很好:

I'd like to test some property about it with quickcheck. Though, I'm not interested in testing negative values of Integral types because I'm using Integer by lack of a Natural type in the base library. So I thought, let's take the opposite of the value generated when the value generated is negative and I'll be fine:

prop_id :: (Integral a, Show a, Read a) => Positive a -> Bool
prop_id n | n >= 0    = (rev.rev) n == n
          | otherwise = let n' = -n in (rev.rev) n' == n'

(被测试的财产在这里并不重要 - 特别是它不适用于非常基本的价值,我意识到这一点,这不是这个问题的主题)

(the property tested isn't important here - in particular it doesn't hold for very basic values and I'm aware of that, it's not the subject of this question)

然后我遇到了 Positive 修饰符,并认为虽然我的测试现在正在运行,但以更好的方式实现它会更好。所以我试过:

Then I ran into the Positive modifier and thought that although my test was now functionning, it'd be nice to implement it in a nicer way. So I tried:

prop_id :: (Integral a, Show a, Read a) => Positive a -> Bool
prop_id n = (rev.rev) n == n

我必须承认我编译时感到惊讶。但是当运行测试时弹出一个错误:

I must admit I was surprised when it compiled. But then an error popped when running the test:

*** Failed! Exception: 'Prelude.read: no parse' (after 1 test): 
Positive {getPositive = 1}

所以我想,mmk,必须声明这个 Positive 事物是 Read >的一个实例。所以我就这么做了,但是这个实例已经在quickCheck库中声明了,因为ghci对我发出了尖叫。

So I thought, "mmk, must declare this Positive thing an instance of Read". So I did just that, but the instance is already declared in the quickCheck library it seems because ghci screamed at me.

此时我迷路了,因为我没有找到好的文档(如果有的话)。

And at this point I'm lost, for I do not find good documentation (if any).

任何可以帮助我理解quickcheck库中的修饰符和其他好东西的指针都会被赞赏。 $ b

Any pointer helping me to understand modifiers and other nice things in the quickcheck library will be appreciated.

推荐答案

使用这些修饰符的常用方法是对它们进行模式匹配,例如

The common way of using these modifiers is to pattern match on them, e.g.

prop_id :: (Integral a, Show a, Read a) => Positive a -> Bool
prop_id (Positive n) = (rev.rev) n == n

方式, n 将具有基础类型。

This way, n will have the underlying type.

这篇关于如何在Quickcheck中使用修饰符(在我的情况下为正数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆