0

I want to create Generator from multiple generators. I have list of generators

val generators: List[Gen] = List(Gen[Int], Gen[Double], Gen[String], ...)

I don't know what is the size of the list, it could be any size

I want to create something like this:

val listGen: Gen[List[Any]] = createListGenerator(generators)
Mahmoud Hanafy
  • 1,614
  • 1
  • 22
  • 30
  • 1
    `val listGen = Gen.sequence(generators)`? – danielnixon Feb 16 '16 at 05:47
  • I found it like this: val listGen: Gen[util.ArrayList[Nothing]] = Gen.sequence(generators) , I want it to by : Gen[List[Any]] – Mahmoud Hanafy Feb 16 '16 at 08:58
  • Getting `Gen[util.ArrayList[Nothing]]` is odd. Are you sure you're not seeing `Gen[java.util.ArrayList[Any]]`? Is the type of `generators` `List[Gen[Any]]` or something else? – badcook Feb 16 '16 at 09:28

2 Answers2

1

If you want listGen to give you an arbitrary number of elements in an arbitrary order that are drawn from one or more of the generators in generators, you can do the following:

// Scala's type inference gets a bit finicky when combining Anys with CanBuildFroms
val comboGen = Gen.sequence[List[Any], Any](generators).flatMap(Gen.oneOf[Any])
val listGen = Gen.listOf(comboGen)

Alternatively, if you want to have exactly the same number of elements get generated by listGen as there are elements in generators and in the same order, you can simply do

val listGen = Gen.sequence[List[Any], Any](generators)
badcook
  • 3,619
  • 11
  • 25
0

We start with a list of generators

val generators: List[Gen[Any]] = ???

Next we create a generator which generates elements by choosing one generator and yielding the item generated by that generator:

val genOne: Gen[Any] = for {
  gen <- Gen.oneOf(generators)
  item <- gen
} yield item

We can use this generator to create a list generator

val listGen: Gen[List[Any]] = Gen.listOf(genOne)

This list generator generates a list (possibly empty) which can contain items generated by the generators in the original generators List, however not all generators are always included, and the order is random.

For example if the generators List contained a Gen[Int], Gen[Double] and a Gen[String], then the lists generated by listGen. Will contain any amount of ints, doubles and strings in any order.

Wellingr
  • 1,132
  • 1
  • 9
  • 19