Skip to content

Instantly share code, notes, and snippets.

@ebiggs
Last active December 12, 2015 07:08
Show Gist options
  • Save ebiggs/4734014 to your computer and use it in GitHub Desktop.
Save ebiggs/4734014 to your computer and use it in GitHub Desktop.
Feeling the love for flatMap lately...

Been really loving flatMap lately. I used to mostly regard it for its usefulness in its relationship to scala's for comprehensions but I'm now kind of loving it for its use as a "subtractive" and "additive" map. What I mean is that when working with Sequences you can flatMap to Seq() to get rid of something or to a Seq( ... ) if you want to split something into multiple things. Basically flatten its inherent composition. Here's a lil gist illustrating the idiom. The idea is you have a sequence of Good ('G), Neutral ('N), and Bad ('B) vibes. After the party the bad vibes are gone and the good vibes have doubled, leaving the neutral vibes unchanged. The party1 function illustrates a more linear way of thinking about the party and party2 represents some flatMap magic :). Personally I think party2, though more verbose, represents a clearer reflection of the process. It seems a bit more illustrative/declarative of what the point of the party is. The result of Party2 also has a nicer order to it.

scala> val vibes = Seq('G,'B,'N,'G,'B,'B,'G,'N,'N)
vibes: Seq[Symbol] = List('G, 'B, 'N, 'G, 'B, 'B, 'G, 'N, 'N)

scala> def party1(vibes: Seq[Symbol]) = 
  vibes.filter(_ != 'B) ++ vibes.filter(_ == 'G)

party1: (vibes: Seq[Symbol])Seq[Symbol]

scala> def party2(vibes: Seq[Symbol]) = vibes.flatMap { 
  case 'N => Seq('N) case 'B => Seq() case 'G => Seq('G, 'G) 
}

party2: (vibes: Seq[Symbol])Seq[Symbol]

scala> party1(vibes)
res2: Seq[Symbol] = List('G, 'N, 'G, 'G, 'N, 'N, 'G, 'G, 'G)

scala> party2(vibes)
res3: Seq[Symbol] = List('G, 'G, 'N, 'G, 'G, 'G, 'G, 'N, 'N)

scala> 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment