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?
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With