FP for Sceptics: Intuitive guide to map/flatmap
Backbone of Functional Programming
map & flatmap form the backbone of Functional Progamming. It is very important be comfortable with these two concepts and this guide will help you develop an intuition for them.
This guide is language agnostic but I expect you to be familiar with basic programming concepts like functions, types, data type/objects and list.
Nomenclature
Let me introduce you to some basic terms we will be using to talk about map/flatmap.
-
Types are data constructs and they can beBasic Typeslike Int, String etc. -
Containeris a specialtypewhich contains anothertype. For example a List of Ints. -
Functionis a function whose input is of Type 1 and output is of Type 2. Type 1 & Type 2 can be same type.
Visualize
Though I have defined three terms it will be easier to think about them visually.
Basic types (Int, String etc) will be represented by shapes
.
Containers will be represented by shapes

In reality, we will always use
Container for a Type

etc.
Functions will be denoted as

Verbalize
Let's see how to verbalize these terms:
Container for Triangle
Square for Circle for Triangle
f is a function from Triangle to Star
g is a function from Triangle to Container of Triangle
Fundamentals
In this section, I want to introduce one basic concept along with map/flatmap.
Function Composition
Function Compositionis chaining two or more functions such that output of one function feeds into to the input of second function and so on.

map
mapis a function that takes a Container (C1) & a Function (F) as input and returns a new Container (C2) for Function's (F) output type.
Rules for map
- Type contained by Container (C1) has to match Function's (F) input type.

flatmap
flatmapis a function that takes a Container (C1) & a Function (F) as input and returns a new Container (C2) for Function's (F) output type.
Rules for flatmap
- Type contained by Container (C1) has to match Function's (F) input type.
- Function (F) has to return a Container (C2)
- C1 == C2. This is very important to remember as many people trip up on this.

Note: As you can see, both
map&flatmaphave the same written definition but the strictness is in the rules it has to adhere to.
Exercise Problems
Let's conclude with a few exercise problems.
Problem Set: Map

Solutions
-
-
- Error! Breaks the rule for map
- Error! map works on a Container, not a Basic Type
Problem Set: FLatMap

Solutions
-
-
- Error! Breaks the 2nd Rule for flatmap
Problem Set: Advanced FlatMap

Solutions
Conclusion
I hope after going through this guide, you are more comfortable working with map/flatmap.
If you liked this guide, have a look at the rest of my posts on FP (in Scala) - FP for Sceptics
g is a function from Triangle to Container of Triangle