Tuesday 20 March 2012

Map, Flatten and FlatMap

I've recently been working with some developers who are new to the Scala world. They've picked up the language really easily and in only a few week have become competent Scala developers. Who says it's too complex and difficult to learn?

Anyway, one of these developers is a visual thinker such as myself. We prefer communication through diagrams rather than words. While explaining Scala I've been drawing some pictures to illustrate some of the more interesting concepts. She suggested that I should publish these and we had the idea that an animation would be fun.

Here's my first animated post showing the concepts for Map, Flatten and FlatMap. It's a pretty amiturish stab at animation, but hopefully it explains the concepts while also adding a bit of humour along the way.

If you are interested here's the Scala code for the concepts covered in the animation:

case class World[+A](revolvesAround: A) {

  def map[B](f: A => B): World[B] = World(f(revolvesAround)) 

  def flatten[B](implicit ev: A <:< World[B]): World[B] = World(revolvesAround.revolvesAround)

  def flatMap[B](f: A => World[B]) = World(f(revolvesAround).revolvesAround)

  def get: A = revolvesAround
}

def lift[A](entity: A): World[A] = World(entity)

case class Person(name: String) {
  def smite = DeadBody(name)
}
case class DeadBody(usedToBe: String)
case class Insect(species: String)

def kill(p: Person): DeadBody = p.smite
def reincarnate(b: DeadBody): World[Insect] = World(Insect("ant"))

val dave: Person = Person("Dave")
val antDave: Insect = lift(dave) map kill flatMap reincarnate get 

println(antDave)

4 comments:

  1. I like your style. Dave could be the new Elvis!

    ReplyDelete
  2. It's amazing!

    ReplyDelete
  3. Nice one!

    There's a small mistake where you define a "smite" method on Person but later call it as "kill"

    ReplyDelete
  4. Very nice example, this is really one of the better explained Scala functional examples! Thanks for posting :-)

    ReplyDelete