top of page

Three basic functions in functional programming (Python)

There are three functions that facilitate functional programming: map, filter and reduce. To explain three functions, I will tell you story about Snow White and the seven Dwarfs. Of course, almost children know this fairy story, but do you know what the seven Dwarfs do? They mine ores, and I will tell you about their work.

1. Excavation - mapping

At the first stage, Each Dwarf excavate the surface of the rock and get potential ores. The mapping is a function as excavation of Dwarfs. Map applies a function (excavation) to all items in an input list (the surface of the rock) and return an same-size output list (ores in the carts).

Example:

Output:

2. Filtering

After collecting the small pieces of rock, they remove scree and keep gemstone from the carts. The filter function also filters based on a specific condition (whether it is gemstone?), which removes elements (scree) that do not satisfy the condition and keeps elements (gemstone) that satisfy the condition.

Example:

Output:

3. Loading - Reduce

The night is coming, and seven dwarfs put gems into carts to bring to warehouse. They use connector to bridge cart each other and load to warehouse.

The 'Reduce' function is similar the seven dwarfs' work. This function performs 'rolling' computation (connect a pair of carts as a chain) on sequential pairs in the input list (pair of carts) and returns the result (put gems to the warehouse).

Example:

Output:​​ 15

Featured Posts
Check back soon
Once posts are published, you’ll see them here.
Recent Posts
Archive
Search By Tags
No tags yet.
Follow Me
  • Blogger - Black Circle
  • Google+ - Black Circle
  • LinkedIn - Black Circle
bottom of page