Original The functional programming of the beginner learning of Python

Source: Internet
Author: User
Tags iterable

A preface

The first contact functional programming is in the study of distributed computing, when the map/reduce is unknown to the Li, but also did not understand how many principles of things. Functional programming in Python is also an initial look at Map/reduce. The so-called functional programming, in essence, can be attributed to process-oriented programming, but its thinking is very close to mathematical calculation. It is more abstract than the normal programming paradigm, and functions written in purely functional programming languages are non-variable, and as long as the input is determined, the output is determined. Another feature of this is that the function itself is passed into another function as a parameter, allowing a function to be returned.

Two higher order functions (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 by this variable. In a process-oriented program design using Python, a function with a variable is a very common design, but if the variable is a function, then the function with the variable is called the high-order function.

A simple example of a higher order function:

def fun (n):    return n+1def highorder (x, Y, f):    return F (x) +f (y)

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

Three Map/reduce

With the above higher-order function basis, it is now easy to understand Map/reduce. The map function receives two parameters, one is a function and the other is iterable. The map functions on each element of the iterable in sequence and returns the result as a new iterator.

Look at the following example:

def fun (n):    return N*2m=map (fun, [1,2,3,4,5]) print (m) E:\study\python>python hello_python.py[2, 4, 6, 8, 10]

Map functions fun in sequence on each element of the list and gets [2,4,6,8,10].

If it is 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])

Let's look at the usage of reduce. Reduce, like map, also functions a function sequentially on a sequence, but requires that the function must receive two functions. Reduce then functions on the result of the first two parameters and on the elements of the next sequence.

The following example uses reduce to achieve a sequence sum operation, as shown below:

def add (x, y):    return X+yr=reduce (Add, [1,2,3,4,5]) print (r) E:\study\python>python HELLO_PYTHON.PY15

Its lambda version is:

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

Four return functions

As already stated above, a function can be assigned to a variable, since the function can return a variable and, of course, it can return a function. Although the return variable and the return function are not very different in nature, the mechanism of the return function has great effect in the application.

Consider the following example:

def wrapper (*param):    def calc ():        sum=0 for        x in param:            sum=sum+x        return sum                return calc;f= Wrapper (1,2,3,4,5) print (f ()) E:\study\python>python HELLO_PYTHON.PY15

Defines a parcel function wrapper, receiving an indefinite number of parameters. When this function is called, it returns an internally defined function that is executed only when it is actually called. Also note that the data accessed in the Calc function is brought in by wrapper, and these parameters are saved with Calc, which we call "closures" (closure).

Five closures (Closure)

The initial contact closure is not a very understanding of it. Still use the code in four as an example.

Wrapper is a function that includes an indefinite number of parameter param. The special place is that the function body also defines a new function, Calc, the function body of the new function is referencing an external function wrapper parameters, that is, the parameters passed by the external function has been bound with the Calc function to form a new function. We can think of Param as a configuration information for this new function. Configuration information If it is not the same, the output of the function will of course be different.

For a better understanding of closures, look at the following code example:

def wrapper (conf):    def calc (n):        return conf+n    return Calcf1=wrapper (1) f2=wrapper (2) print (F1) print (F2 (100)) E:\study\python>python hello_python.py101102

Parsing the above code, calling wrapper (1) Returns a function, and the function's configuration information is conf with a value of 1. Another function is returned when calling wrapper (2), and the configuration information for this function is conf with a value of 2. So in the subsequent we all pass 100 parameters to call F1 and F2 when the result is 101 and 102, the root cause is that the configuration information of two functions is different.

  It is worth noting that not all the information of an external function is configured by the internal function, only the parameters of the external function are used as configuration information by the intrinsic function. As for the local variables of the external functions, they are not configured as configuration information.

    

Six decorators (Decorator)

The original intention of inventing decorator is to solve the problem of adding other functions before and after a function call, such as printing logs, without modifying the original function code. Decorator is essentially a high-order function that returns a function, see the following decorator of the print log, the code is as follows:

def decorator (func):    def wrapper ():        print ("before invoked:")        func ()        print ("after invoked:")    Return wrapper        def func ():    print ("Func invoked:")  F=decorator (func) F () E:\study\python>python Hello_ Python.pybefore Invoked:func Invoked:after invoked:

The above code defines a adorner for func, which returns a function when the adorner is called, and then calls Func when the required code is added to the function. But here's the problem, that is, you can call Func directly, but now you're going to call F. It is easy to solve this problem, because in Python the function can be assigned to a variable, just change F to func. As shown below:

Func=decorator (func) func ()

Python provides a syntax for implementing this mechanism: @. Adding @decorator to the Func is equivalent to executing the Func=decorator (func), which solves the code that uses the same name to invoke the added functionality. As shown below:

def decorator (func):    def wrapper ():        print ("before invoked:")        func ()        print ("after invoked:")    return wrapper        @decoratordef func ():    print ("Func invoked:")  func ()

There is also how to add parameters to decorator and how to modify the contents of the wrapper __name__ property to Func, which is not described here.

Seven partial functions (partial function)

What is a partial function? A partial function is a function that adds a default parameter to a function. In Python, you can use functools.partial to generate a function's partial function. Take an int () in Python as an example, the Int () function is converted by decimal by default, and if you want to generate a partial function that is converted by 8, you can do so as follows:

print (int (' 12345 ')) int8=functools.partial (int, base=8) print (int8 (' 12345 '))

Eight summary

In this article, we mainly describe several basic concepts in functional programming. The most difficult thing for a person to understand is decorator, especially the so-called configuration information. If there is a mistake, please leave a message!!!

Original The functional programming of the beginner learning of Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.