FlatMap in generator from scala online course Martin Oderski

I am currently studying the online course "Principles of Reactive Programming", Martin Oderski, Eric Meyer, Roland Kuhn, which already ended a year ago, I think no one is participating in the discussion forum of this course, so I really hope for help in this issue.

In the Functional Random Generators session, Martin gives a generator implementation with flatMap methods, like:

trait Generator[+T] {
  self => // an alias for "this"

  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
  }
}

      

I don't quite understand that here FlatMap returns a new generator [S] with a specific generation method, but the implementation of which depends on a "different" generation method from a "different" generator [S] from the input function the argument f.

Here are my questions:

1) Are the generator [S] the input function f and the generator [S] returned by this flatMap method of the same type?

2) If they are the same, then how is the generation method interpreted by the compiler since it is defined by itself?

+3


source to share


1 answer


I think I got the answer

1) the generator [S] from the input function f and the generator [S] returned by the flatMap method are of the same abstract type, but their instances can have different subtypes, and therefore the "virtual" generation methods are different,



2) The method of generating the returned generator [S] from the input function f must already be defined in the context of flatMap. They are different generation methods from different real types.

+1


source







All Articles