Python introductory learning functional programming

黄舟
Release: 2016-12-16 16:36:37
Original
1041 people have browsed it

1 Preface

The first time I came into contact with functional programming was when I was learning distributed computing. At that time, I didn’t know much about map/reduce and didn’t understand much about the principles. Functional programming in Python can also be regarded as a preliminary understanding of map/reduce. The so-called functional programming can essentially be attributed to process-oriented programming, but its ideas are very close to mathematical calculations. It is more abstract than the general programming paradigm, and functions written in purely functional programming languages ​​have no variables. As long as the input is determined, the output is determined. Another feature of it is that the function itself is passed as a parameter to another function, allowing a function to be returned.

2 High-order Function

In Python, the function name is essentially a variable. We can assign a function name to a variable and then call the function through this variable. In process-oriented programming using Python, a function with variables is a very common design, but if the variable is a function, then this function with variables is called a higher-order function.

 A simple example of a higher-order function:

def fun(n):
return n+1

def highorder(x, y, f):
return f(x)+f(y)

above The defined higherorder is a higher-order function, which is a function that can receive other functions in parameters.

Three Map/Reduce

With the above high-order function foundation, it is easy to understand Map/Reduce now. The Map function receives two parameters, one is a function and the other is an Iterable. Map applies the function to each element of the Iterable in turn and returns the result as a new Iterator.

Look at the example below:

def fun(n):
return n*2

m=map(fun, [1,2,3,4,5])PRint(m)

E:Studypython> python hello_python.py
[2, 4, 6, 8, 10]

Map applies the function fun to each element of the list in turn, and we get [2,4,6,8,10].

 If you find it troublesome to define a fun function, you can use lambda to simplify it, as follows:

m=map(lambda n:n*2, [1,2,3,4,5])

Look again How to use Reduce. Like Map, Reduce also applies a function to a sequence in sequence, but it requires that this function must receive two functions. Reduce then applies the function to the result of the first two parameters and the next element of the sequence.

  Now use Reduce to implement a sequence summation operation, see the following example:

def add(x,y):
return x+y

r=reduce(add, [1,2,3,4, 5])
print(r)

E:Studypython>python hello_python.py
15

Its lambda version is:

r=reduce(lambda x,y:x+y, [1,2,3 ,4,5])

Four return functions

As mentioned before, a function can be assigned to a variable, so since the function can return a variable, of course it can also return a function. Although there is not much difference between returning variables and returning functions, this mechanism of returning functions plays a great role in applications.

 Look at the following example:

def wrapper(*param):
  sum=0
    sum=sum+x
   return sum                                                        return calc;

f= wrapper(1,2,3,4,5)

print(f())

E:Studypython>python hello_python.py
15


Define a wrapper function wrapper that receives an indefinite number of parameters. After calling this function, it returns an internally defined function that will be executed when it is actually called. Also note that the data accessed in the calc function is brought in by the wrapper, and these parameters will be saved together with calc, which we call "closure".

5 Closure

When I first came into contact with closures, I didn’t quite understand them. Still using the code in Part 4 as an example.

 The wrapper is a function, including an indefinite number of parameters param. What is special is that a new function calc is also defined in this function body. The function body of this new function refers to the parameters of an external function wrapper. In other words, the parameters passed by the external function have been bound to the calc function. Together, a new function is formed. We can think of param as a configuration information of this new function. If the configuration information is different, the output of the function will of course be different.

 To better understand closures, look at the following code examples:

def wrapper(conf):

def calc(n):

  return conf+n

return calc

f1=wrapper(1)
f2=wrapper (2)

print(f1(100))
print(f2(100))

E:Studypython>python hello_python.py
101
102

Analyzing the above code, when calling wrapper(1), a function will be returned, and the configuration information of this function is that the value of conf is 1. When wrapper(2) is called again, another function will be returned, and the configuration information of this function is that the value of conf is 2. So when we later pass in 100 parameters to call f1 and f2, the results we get are 101 and 102. The fundamental reason is that the configuration information of the two functions is different.

It is worth noting that not all the information of the external function will be used as configuration information by the internal function. Only the parameters of the external function will be used as configuration information by the internal function. As for the local variables of external functions, they will not be used as configuration information.

  

6 Decorator

 The original intention of inventing Decorator was to add other functions before and after function calls, such as printing logs, etc. without modifying the original function code. Decorator is essentially a higher-order function that returns a function. Look at the decorator that prints logs. The code is as follows:

def decorator(func):
def wrapper():
print("Before invoked:")
func() A Print ("After Invoked:")
Return wrapper

Def Func ():
Print ("Func Invoked:") python. py
Before invoked:
Func invoked:
After invoked:


The above code defines a decorator for func. When calling this decorator, it returns a function. Add the required code to this function and then call func. But there is a problem here, that is, func could be called directly, but now f is called. It is easy to solve this problem, because in python a function can be assigned to a variable, just change f to func. As shown below:

func=decorator(func)
func()

Python provides a syntax to implement this mechanism: @. Just add @decorator before func, which is equivalent to executing func=decorator(func). This solves the problem of using the same name to call the code after adding the function. As shown below:

def decorator(func):

def wrapper():
print("Before invoked:")
func()

print("After invoked:")

return wrapper

@dec orator
def func ():
print("Func invoked:")

func()


In addition, there are also how to add parameters to the decorator and how to modify the __name__ attribute of the wrapper to func, which will not be described here.



7 Partial Function

What is a partial function? A partial function is a function that adds default parameters to the function. In python, you can use functools.partial to generate the partial function of a function. Take int() in python as an example. The int() function defaults to decimal conversion. If you want to generate a partial function that converts to octal, you can implement it as follows:

print(int('12345'))

int8=functools.partial(int, base=8)

print(int8('12345'))


Eight summary

 In this article, we mainly talk about several basic concepts in functional programming. Personally, I feel that the most difficult thing to understand is Decorator, especially the so-called configuration information. If there are any errors, please leave a message! ! !

The above is the content of functional programming for introductory learning in Python. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template