Examples of functional programming in python

  • 2020-04-02 13:44:34
  • OfStack

Functional programming is the use of a series of functions to solve a problem, according to the general thinking of programming, we face the problem is "how to do", while functional programming is the way I want to "do". As for the characteristics of functional programming is not summarized, we directly take examples to understand what is functional programming.

Lambda expression (anonymous function) :

The definition of ordinary function and anonymous function:


# Common function 
def add(a,b):
    return a + b
print add(2,3)

# Anonymous functions 
add = lambda a,b : a + b
print add(2,3)

#======== The output ===========
5

The naming rule of the anonymous function is identified by the lamdba keyword. The left side of the colon (:) indicates the parameters (a,b) that the function receives, and the right side of the colon (:) indicates the return value of the function (a+b).

Because lamdba does not need to be named when it is created, it is called the anonymous function ^_^

The Map function: Calculate string length


abc = ['com','fnng','cnblogs']
for i in range(len(abc)):
    print len(abc[i])
#======== The output ===========
4

Define an array of ABC strings, calculate the length of ABC and loop out the length of each string in the array.

Let's see how the map() function implements this.


abc_len = map(len,['hao','fnng','cnblogs'])
print abc_len
#======== The output ===========
[3, 4, 7]

Although, the output is the same, but they have different forms, the first is purely numeric, the map() function output still retains the array format.

Case conversion;

Python provides upper() and lower() to convert case.


# Case conversion 
ss='hello WORLD!'
print ss.upper()  # Convert to uppercase 
print ss.lower()  # Convert to lowercase 
#======== The output ===========
HELLO WORLD!
hello world!

Transform through the map() function:


def to_lower(item):
    return item.lower()
name = map(to_lower,['cOm','FNng','cnBLoGs'])
print name
#======== The output ===========
['com', 'fnng', 'cnblogs']

As you can see in this example, we've written a function called toUpper, which doesn't change the value passed in, just takes the value passed in and returns it. Then, using this in the map function, we can clearly describe what we want to do.

Let's take a look at how string case conversion is implemented in a common way:


abc = ['cOm','FNng','cnBLoGs']
lowname = []
for i in range(len(abc)):
    lowname.append(abc[i].lower())
print lowname
#======== The output ===========
['hao', 'fnng', 'cnblogs']

The map() function plus lambda expressions (anonymous functions) provides even more power.


# square 
#0*0,1*1,2*2,3*3,....8*8
squares = map(lambda x : x*x ,range(9))
print squares
#======== The output ===========
[0, 1, 4, 9, 16, 25, 36, 49, 64]

The Reduce function:


def add(a,b):
    return a+b
add = reduce(add,[2,3,4])
print add
#======== The output ===========

For the Reduce function, it is necessary to process two data at a time. The first choice is 2 and 3, and the result is 5 after adding by the add function, followed by 5 and 4, which are processed by the add function, and the final result is 9.

As you can see from the previous map function example, the map function only processes one data at a time.

 

Then, we find how easy it is to implement factorial by using Reduce function and lambda expression:


#5 factorial 
#5 ! =1*2*3*4*5
print reduce(lambda x,y: x*y, range(1,6))
#======== The output ===========

In addition to map and reduce, there are other functions in Python, such as filter, find, all, and any (other functional languages also have them), which can make your code cleaner and easier to read. Let's look at a more complicated example:


# Calculates the value of a positive integer in the array 
number =[2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8]
count = 0
sum = 0
for i in range(len(number)):
    if number[i]>0:
        count += 1
        sum += number[i]
print sum,count
if count>0:
    average = sum/count
print average
#======== The output ===========
6

In functional programming, the example can be written like this:


number =[2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8]
sum = filter(lambda x: x>0, number)
average = reduce(lambda x,y: x+y, sum)/len(sum)
print average
#======== The output ===========

Finally, we can see that functional programming has the following benefits:

1) the code is simpler.
2) data sets, operations and return values are all put together.
3) when you read code, there is no loop body, so there are fewer temporary variables, and the logic of variable back-and-forth.
4) your code becomes a description of what you do, not how you do it.


Related articles: