Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the map/flatmap function used in for comprehensions?

Tags:

scala

flatmap

I want to see the f function that is getting passed in map/flatmap, but no luck. I threw an an exception to see any sign of f, did not work. What is that function? how is it generated behind the scenes?

Exception in thread "main" java.lang.RuntimeException
   at x.x.Main$A.getInt(Empty.scala:8)
   at x.x.Main$A.flatMap(Empty.scala:10)

object Main extends App {

  class A {
    def getInt: Int = throw new RuntimeException
    def map(f: Int => Boolean): Boolean = f(getInt)
    def flatMap(f: Int => Boolean): Boolean = f(getInt)
  }

  for {
    x <- new A
    y <- new A
  } yield x == y
}
like image 563
mert inan Avatar asked Jan 15 '14 14:01

mert inan


1 Answers

The equivalent code for your for-comprehension

for {
  x <- new A
  y <- new A
} yield x == y

is like this:

new A().flatMap{ x => new A().map{ y => x == y } }

You could use scalac -Xprint:parser main.scala to get code generated from your for-comprehension. In this case you'll get this:

new A().flatMap(((x) => new A().map(((y) => x.$eq$eq(y)))))

You could also get it in REPL without addition macro like this:

import reflect.runtime.universe._

show{ reify{
  for {
    x <- new A
    y <- new A
  } yield x == y
}.tree }
// new $read.A().flatMap(((x) => new $read.A().map(((y) => x.$eq$eq(y)))))
like image 162
senia Avatar answered Nov 01 '22 17:11

senia