scala - Defining a ScalaCheck generator in terms of another Gen -
how define generator in produce random data fields
of given block
. following scaffolding code. need expression replace ???
. expression should generate seq[field]
, field
should generated using defined genfield
function.
def blockgen(b: block): gen[block] = { id <- b.blockid //use same blockid b fields <- ??? //get type each field , call genfield } yield block(id, fields)
adt
trait data {} trait field extends data { val name: string val value: string } case class stringfield(name: string, value: string) extends field case class numberfield(name: string, value: string) extends field case class block(blockid: field, fields: seq[field]) extends data
generators
def fieldgen(fieldtype: field): gen[field] = { { f <- fieldtype match { case _: numberfield => numgen case _: stringfield => strgen } } yield f } val strgen: gen[stringfield] = { name <- gen.identifier value <- gen.alphastr } yield stringfield(name, value) val numgen: gen[numberfield] = { name <- gen.identifier value <- gen.numstr } yield numberfield(name, value)
sample block: myblock
val cx = new stringfield("blockid", "cx") val seg = stringfield("segmentation", "abc") val ver = numberfield("version", "1.0") val myblock = block(cx, seq(seg, ver))
i believe you're looking gen.sequence
.
also, id
doesn't need come generator, since you're doing using particular value directly.
def blockgen(b: block): gen[block] = { fields <- gen.sequence[seq[field], field](b.fields.map(fieldgen)) } yield block(b.blockid, fields)
by way, gen.sequence
similar future.sequence
, sequence
in haskell.
Comments
Post a Comment