Saturday, July 29, 2017

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:

   def add_one(x):
    return (x+1)
items = [1, 2, 3, 4, 5]
result = list(map(add_one, items))
Output: [2, 3, 4, 5, 6]

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:

   def is_even(x):
    return (x%2) == 0
items = [1, 2, 3, 4, 5]
result = list(filter(is_even, items))
Output: [2, 4]

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:
 def sum(x,y):
    return (x + y)
items = [1, 2, 3, 4, 5]
result = reduce(sum, items)
Output: 15

No comments:

Post a Comment

Explanation of self-attention (single head)

Attention (*Source: https://jasperwalshe.com/perspective-and-performance/) 1. Main ideas Convolutional neural networks (CNN) only f...