本文介绍了使用scalacheck生成任意(合法)Unicode字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试创建一个生成器,该生成器使用scalacheck 1.6.6和specs 1.7(scala 2.8.1)生成(非零长度)合法的unicode字符串.

I'm trying to create a generator that produces (non-zero-length) legal unicode strings, with scalacheck 1.6.6 and specs 1.7 (scala 2.8.1).

我希望我可以创建像这样的生成器:

I hoped I could just create generators like:

object Generators {
  def unicodeChar: Gen[Char] =
    choose(Math.MIN_CHAR, Math.MAX_CHAR).map(_.toChar).filter(
      c => Character.isDefined(c))
  def unicodeStr: Gen[String] = for(cs <- listOf1(unicodeChar)) yield cs.mkString
}

...然后从类似的规格中使用它们:

...then use them from specs like:

import org.specs.Specification
import org.specs.matcher.ScalaCheckMatchers

object CoreSpec extends Specification with ScalaCheckMatchers {
  "The core" should {
    "pass trivially" in {
      Generators.unicodeStr must pass((s: String) => s == s)
    }
  }
}

但是,似乎在unicodeChar中使用过滤器会导致问题:

But, it seems that using filter in unicodeChar causes a problem:

Specification "CoreSpec"
  The core should
  x pass trivially
    Gave up after only 64 passed tests. 500 tests were discarded.

如果我从unicodeChar中删除过滤器,则测试会通过,但是由于我的字符串并非始终是定义良好的unicode,因此以后我还会遇到其他问题.

If I remove the filter from unicodeChar, my test passes, but I run into other problems later, since my strings are not always well-defined unicode.

预先感谢您提供有关实现此目标的任何建议.

Thanks in advance for any suggestions on how to achieve this.

推荐答案

在创建生成器之前尝试过滤掉字符:

Try filtering out the characters before creating the generator:

val unicodeChar: Gen[Char] = Gen.oneOf((Math.MIN_CHAR to Math.MAX_CHAR).filter(Character.isDefined(_)))

这将占用更多的内存,因为在创建生成器时将分配完整的Unicode字符列表,但是将只使用该列表的一个实例,因此这不是什么大问题.

It will be more memory intensive, since the complete list of unicode characters will be allocated when the generator is created, but only one instance of that list will be used so it shouldn't be a big problem.

这篇关于使用scalacheck生成任意(合法)Unicode字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:57