Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala flatmap signature definition

Maybe I don't understand some fundamentals, but what is the signature of flatMap in general? Let's imagine I'd like to implement type T supporting for expression, then I required map, flatmap and withFilter implemented by T. Is there any interface of something like that?

More precisely what is the source of the signature:

class T[+A] {

    def flatMap[B](f: (A) => T[B]): T[B]

}

Or is it a definition? May I implement flatmap with different signature?

like image 263
sh1ng Avatar asked Feb 15 '23 18:02

sh1ng


1 Answers

In general flatMap has signature:

class T[+A] {

def flatMap[B](f: (A) ⇒ T[B]): T[B]
def map[B](f: (A) ⇒ B): T[B]

}

For example for Option:

def flatMap[B](f: (A) ⇒ Option[B]): Option[B]

For Seq:

def flatMap[B](f: (A) ⇒ Seq[B]): Seq[B]

Of course in scala API you will see other signatures for Seq, List - because there is generic signature in trait TraversableLike for all collections.

For monad function map should:

m map f == m flatMap (x => unit(f(x)))

Where unit unit(x) = single(x), for example:

  • List is a monad with unit(x) = List(x)
  • Set is monad with unit(x) = Set(x)
  • Option is a monad with unit(x) = Some(x)

Update There is no interface for flatMap/map. See example (copy to your REPL):

class C[+A](val a:A) { 
 def flatMap[B](f:(A) => C[B]):C[B] = f(a)
 def map[B](f:(A)=>B):B = f(a)
}

Then call in REPL for method:

scala> for { k<- new C(3)} yield {k}
res2: Int = 3
like image 194
Andrzej Jozwik Avatar answered Feb 23 '23 19:02

Andrzej Jozwik