简体   繁体   English

如何在Quickcheck中使用修饰符(在我的情况下为正)

[英]How to use modifiers with Quickcheck (Positive in my case)

I've a function, rev , that returns some value for a type that is in three typeclasses: 我有一个函数rev ,它为三个类型类中的类型返回一些值:

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

I'd like to test some property about it with quickcheck. 我想通过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. 虽然,我对测试Integral类型的负值不感兴趣,因为我在基础库中缺少Natural类型而使用Integer 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) (测试的属性在这里并不重要 - 特别是它不适用于非常基本的值,我知道这一点,它不是这个问题的主题)

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. 然后我遇到了Positive修饰符,并认为虽然我的测试现在正在运行,但以更好的方式实现它会很好。 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}

So I thought, "mmk, must declare this Positive thing an instance of Read ". 所以我想,“mmk,必须声明这个Positive东西是Read的一个实例”。 So I did just that, but the instance is already declared in the quickCheck library it seems because ghci screamed at me. 所以我做到了这一点,但实际上已经在quickCheck库中声明了实例,因为ghci对我尖叫。

And at this point I'm lost, for I do not find good documentation (if any). 在这一点上,我迷路了,因为我找不到好的文件(如果有的话)。

Any pointer helping me to understand modifiers and other nice things in the quickcheck library will be appreciated. 任何指针帮助我理解quickcheck库中的修饰符和其他好东西将不胜感激。

The common way of using these modifiers is to pattern match on them, eg 使用这些修饰符的常用方法是对它们进行模式匹配,例如

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

This way, n will have the underlying type. 这样, n将具有底层类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM