Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the "flatmap that s***" idiomatic expression in Scala come from?

Tags:

scala

What is so powerful about flatmap that it deserves such a place in the Scala folklore?

like image 491
Guillaume Belrose Avatar asked Dec 19 '11 09:12

Guillaume Belrose


People also ask

How does flatMap work in Scala?

In Scala, flatMap() method is identical to the map() method, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method.

Why do we need flatMap?

It uses One-To-One mapping. It's mapper function produces multiple values (stream of values) for each input value. It's mapper function produces single values for each input value. Use the flatMap() method when the mapper function is producing multiple values for each input value.


1 Answers

The story I heard was that two preeminent Scala programmers were pairing when one of them started writing some code like this:

option match {     case Some ... 

At which point the other said "What is this? Amateur hour? Flat map that shit!"

As to what's so powerful about flatMap, well... First, it's the fundamental monadic operator. That means it is a common operation shared by, for example, containers (such as Option, collections, etc), continuations, state, etc. Second, while you can de-construct an Option, that, as opposed to flatMap, is not a monadic operation, so it cannot be as widely applied. Also, it requires too much knowledge about the data you are manipulating.

Note: previously I said matching was slower than flatMap -- the opposite is true as a matter of fact, up to the most recent version of Scala at the time of this writing, 2.10.1.)

like image 94
Daniel C. Sobral Avatar answered Oct 19 '22 03:10

Daniel C. Sobral