haskell - QuickCheck中的growingElements函数有什么作用?

标签 haskell

当我偶然发现 growingElements 时,我正在浏览 QuickCheck 的文档。功能。那里的文档说

Takes a list of elements of increasing size, and chooses among an initial segment of the list. The size of this initial segment increases with the size parameter. The input list must be non-empty.

这到底是什么意思?当我在 ghci 中尝试这个功能时, 当我一次又一次地运行generate时,它只是返回给定数组中的随机值。我看不出从列表中随机选择和这个函数正在做什么之间有什么区别。

*Main Test.QuickCheck> generate $ growingElements [1..100]
13
*Main Test.QuickCheck> generate $ growingElements [1..100]
53
*Main Test.QuickCheck> 
*Main Test.QuickCheck> generate $ growingElements [1..100]
65
*Main Test.QuickCheck> generate $ growingElements [1..100]
49
*Main Test.QuickCheck> 

有人能更清楚地解释一下这个函数实际上是做什么的吗?

最佳答案

QuickCheck 有一个“大小参数”,用于控制随机生成的输入的大小。它首先生成较小的测试输入,并随着运行越来越多的测试而增加它们。

QuickCheck 手册位于 more detail关于此:

Test data generators have an implicit size parameter; quickCheck begins by generating small test cases, and gradually increases the size as testing progresses. Different test data generators interpret the size parameter in different ways: some ignore it, while the list generator, for example, interprets it as an upper bound on the length of generated lists. You are free to use it as you wish to control your own test data generators.

对于growingElements,大小参数控制随机选择条目时生成器在列表中查看的深度。

如果您想自己使用 size 参数,可以使用 sized 组合器:

sized :: (Int -> Gen a) -> Gen a

这可以让您根据传入的大小编写自己的 Gen a 值。growingElements 可能如下所示:

growingElements' xs = sized (\ size -> oneOf (take size xs))

如果您想查看现有 growingElements 在不同尺寸下的表现,您可以使用 resize 函数修复特定尺寸。尝试一下

resize 1 (growingElements [1..])

它应该只返回列表开头的小数字。 (我查了一下the actual implementation,它使用一些繁琐的算术来根据大小参数选择元素的数量,所以我懒得弄清楚它到底是如何表现的:))。

关于haskell - QuickCheck中的growingElements函数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39441006/

相关文章:

haskell - 在 IO 中处理谓词的惯用 Haskell 方式是什么?

mysql - 是否有使用 haskelldb 或任何其他 haskell 库从现有模式反向工程字段的方法?

haskell - 为什么指向 MVar 的弱指针最终确定了,即使 MVar 仍然可以访问?

haskell - 没有最后一个参数的函数组成

list - 编辑列表中的每个第 N 个项目

programming-languages - Haskell 中的 "class"和 OO 语言中的 "abstract class"有什么区别?

string - 将前导零的haskell Int转换为String

performance - haskell 从 bytestring 中读取成对的向量非常慢,如何让它更快?

json - Yesod Mongo DB 和 JSON

haskell - 我们可以使用 Haskell 与 Razor 引擎进行 Web 开发吗?