简体   繁体   English

如何使用QuickCheck测试函数是否终止?

[英]How do I use QuickCheck to test if a function terminates?

I would like to use QuickCheck to test a function to make sure it terminates (no infinite recursion, no exceptions thrown, etc.). 我想使用QuickCheck来测试一个函数,以确保它终止(没有无限递归,没有抛出异常等)。 This is what I do at the moment: 这就是我现在所做的:

f :: Int -> Int -> Int

prop_fTerminates :: Int -> Int -> Bool   -- say
prop_fTerminates x y = f x y `seq` True

Is there a better (more expressive and idiomatic) way? 是否有更好的(更具表现力和惯用语)的方式?

This is the halting problem . 这是暂停的问题 There is no algorithm capable of telling you whether a function terminates or not. 没有能够告诉您函数是否终止的算法。

In particular, you may be able to get a positive result (ie if the function does terminate, this proposition will tell you) if you are willing to wait long enough. 特别是,如果你愿意等待足够长的时间,你可能会得到一个积极的结果(即如果函数确实终止,这个命题会告诉你)。 But just by waiting, you can never know the difference between this function does not terminate and this function has not terminated yet . 但只是等待,你永远不会知道这个函数没有终止的区别, 这个功能还没有终止

You can implement a check like does this function terminate in time T which may be appropriate for your needs. 您可以执行检查,例如此功能在时间T终止,这可能适合您的需要。


Edit As written, your function does not do what you require. 编辑如上所述,您的功能无法满足您的要求。 Consider 考虑

> let f = 1:f
> f `seq` True
True

The reason is that seq only evaluates to weak head normal form . 原因是seq仅评估弱头正常形式 Instead you could use deepseq which evaluates data structures deeply, 相反,您可以使用deepseq评估数据结构的deepseq

> import Control.DeepSeq (deepseq)
> f `deepseq` True
* never returns *

I probably wouldn't bother, I'd just test other properties of its output. 我可能不会打扰,我只是测试其输出的其他属性。

Any property that examines the output of fxy in any way is going to do at least as much termination checking as your prop_fTerminates , so why waste time doubling up on that check? 以任何方式检查fxy输出的任何属性都将至少与您的prop_fTerminates一样进行终止检查,那么为什么要浪费时间加倍检查呢?

If for some reason "fxy terminates" is the only property you can test about f , then what you've got seems reasonable. 如果由于某种原因“fxy终止”是你可以测试f的唯一属性,那么你所得到的似乎是合理的。

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

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