Scalacheck generate Gen.alphastr with the same length

亡梦爱人 提交于 2019-12-10 12:53:29

问题


I need to generate strings with the same length. I can't realize how. Many thanks

val s = for {
  x <- Gen.alphaStr
} yield ...

回答1:


example code:

import org.scalacheck.Gen
import org.scalacheck.Prop.forAll    

// strGen generates a fixed length random string
val strGen = (n: Int) => Gen.listOfN(n, Gen.alphaChar).map(_.mkString)

val fixedLengthStr = forAll(strGen(10)){ s =>
  s.length == 10
}

fixedLengthStr.check

to inspect a generated string use:

strGen(5).sample



回答2:


There is a suchThat(f: T => Boolean): Gen[T] = new Gen[T] on Gen, so could be used like

val stringShorterThan = (n: Int) => Gen.alphaStr.suchThat(s => s.length <= n)
val string64 = stringShorterThan(64)


来源:https://stackoverflow.com/questions/26808596/scalacheck-generate-gen-alphastr-with-the-same-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!