在ScalaCheck中生成选项[T] [英] Generate Option[T] in ScalaCheck

查看:65
本文介绍了在ScalaCheck中生成选项[T]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ScalaCheck中生成可选参数,但没有成功.

I am trying to generate optional parameters in ScalaCheck, without success.

似乎没有直接的机制. Gen.containerOf[Option, Thing](thingGenerator)失败,因为它找不到隐式的Buildable[Thing, Option].

There seems to be no direct mechanism for this. Gen.containerOf[Option, Thing](thingGenerator) fails because it cannot find an implicit Buildable[Thing, Option].

我尝试了

for {
  thing <- Gen.listOfN[Thing](1, thingGenerator)
} yield thing.headOption

但是这是行不通的,因为listOfN会生成一个列表,该列表的长度始终为N.因此,我总是得到一个Some[Thing].同样,listOf1不起作用,因为(a)它不会产生空列表,而且(b)它效率低下,因为我无法设置元素数量的最大限制.

But this doesn't work because listOfN produces a list that is always of length N. As a result I always get a Some[Thing]. Similarly, listOf1 does not work, because (a) it doesn't produce empty lists, but also (b) it is inefficient because I can't set a max limit on the number of elements.

如何生成不包含任何内容的Option[Thing]?

How can I generate Option[Thing] that includes Nones?

编辑:我找到了一个解决方案,但这并不简洁.有没有比这更好的方法了?

EDIT: I have found a solution, but it is not succinct. Is there a better way than this?

for {
  thing <- for {
    qty <- Gen.choose(0,1)
    things <- Gen.listOfN[Thing](qty, thingGenerator)
  } yield things.headOption
} yield thing

编辑2 :我将其概括为

def optional[T](g: Gen[T]) = 
  for (qty <- Gen.choose(0, 1); xs <- Gen.listOfN[T](qty, g)) yield xs.headOption

因此,我不必多次编写它.但是可以肯定,这已经在图书馆中了,我只是错过了吗?

So I don't have to write it more than once. But surely this is in the library already and I just missed it?

推荐答案

现在您可以使用:

Gen.option(yourGen)

这篇关于在ScalaCheck中生成选项[T]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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