view raw
Javier Javier - 6 months ago 64
Scala Question

Getting random maps from generator code in Scala

I have the following code from the Coursera course Functional Program Design in Scala. It is supposed to be a generator of maps of Int to Int.

lazy val genMap: Gen[Map[Int, Int]] = for {
k <- arbitrary[Int]
v <- arbitrary[Int]
m <- oneOf(const(Map.empty[Int, Int]), genMap)
} yield m.updated(k, v)

My problem is I don't know how to use it. Typing:


does not work. So how can I get maps from Int to Int from this generator?

The trait Generator looks like this (according to the course lectures):

trait Generator[+T]{
self =>
def generate : T
def map[S](f:T=>S):Generator[S] = new Generator[S] {
def generate = f(self.generate)

def flatMap[S](f:T=>Generator[S]):Generator[S] = new Generator[S]{
def generate = f(self.generate).generate


You can use genMap.sample to have a single instance generated. sample does return an Option though, in case it is not possible for your genMap to generate a valid instance.

When using sample in test code I usually just proceed by calling Option.get letting the test crash if no instance can be generated. This indicates that your Gen definition is too strict.