[Original] function programming for getting started with Python, getting started with python

Source: Internet
Author: User

[Original] function programming for getting started with Python, getting started with python

Preface

When I first came into contact with functional programming when I was learning distributed computing, I was not aware of map/reduce at that time, and I didn't know much about the principles. Function programming in Python is also a preliminary understanding of map/reduce. The so-called functional programming can be essentially attributed to process-oriented programming, but its idea is very close to mathematical computing. It is more abstract than the general programming paradigm, and functions written in Pure Functional programming languages do not have variables. As long as the input is determined, the output is determined. Another feature of the function is to pass the function itself as a parameter to another function, allowing the return of a function.

 

High-order Function)

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

A simple high-order function example:

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

The highorder defined above is a high-order function, which can receive other functions in parameters.

 

3. Map/Reduce

With the above high-level functions, it is easy to understand Map/Reduce. The Map function receives two parameters: a function and an Iterable function. Map sequentially applies the function to each element of Iterable and returns the result as a new Iterator.

See 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 are sequentially applied to every element in the list, and then we get [2, 4, 6, 8, 10].

If it is difficult to define a fun function, you can use lambda to simplify it, as shown below:

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

Let's look at the Reduce usage. Similar to Map, Reduce also applies a function to a sequence in sequence, but this function must receive two functions. Reduce then applies the function to the results of the first two parameters and the elements of the next sequence.

The following uses Reduce to implement a sequence summation operation. See the following example:

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])

 

Iv. Return Functions

As mentioned above, a function can be assigned to a variable. Since a function can return a variable, it can also return a function. Although return variables are essentially different from return functions, the mechanism of return functions plays a significant role in applications.

Let's look at 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 the wrapper function and receives a certain number of parameters. After this function is called, it will return an internal defined function, which will be executed only when it is actually called. In addition, the data accessed by the calc function is brought in by wrapper, and these parameters are stored together with calc, which is called closure ).

 

Closure)

I am not very familiar with closures for the first time. The code in section 4 is still used as an example.

Wrapper is a function that includes an indefinite number of parameters (param. In particular, this function body also defines a new function calc. The function body of this new function is referencing the wrapper parameter of an external function. That is to say, parameters passed by external functions have been bound with calc functions to form a new function. We can regard param as a configuration of this new function. If the configuration information is different, the output of the function is certainly different.

To better understand the closure, see the following code example:

def wrapper(conf):    def calc(n):        return conf+n    return calcf1=wrapper(1)f2=wrapper(2)print(f1(100))print(f2(100))E:\Study\python>python hello_python.py101102

After analyzing the code above, a function is returned when wrapper (1) is called, and the configuration information of this function is that the conf value is 1. When wrapper (2) is called, another function is returned, and the configuration information of this function is that the value of conf is 2. Therefore, when we pass in the 100 parameter to call f1 and f2, the result is 101 and 102. The root cause is that the configuration information of the two functions is different.

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

    

Decorator)

The original intention of Decorator was to add other functions before and after function calling without modifying the original function code, such as printing logs. In essence, Decorator is a high-order function that returns the function. The code for viewing the decorator that prints the log 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 code above defines a decorator for func. When calling this decorator, a function is returned. Add the required code to this function and then call func. But there is a problem here, that is, you can directly call func, but now you have to call f. It is easy to solve this problem, because in python, functions can be assigned to a variable. You only need to change f to func. As follows:

func=decorator(func)func()

Python provides a syntax for implementing this mechanism :@. 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 follows:

def decorator(func):    def wrapper():        print("Before invoked:")        func()        print("After invoked:")    return wrapper        @decoratordef func():    print("Func invoked:")  func()

In addition, how to add parameters to the decorator and how to modify the _ name _ attribute of wrapper to func is not described here.

 

Partial Function)

What is a partial function? A partial function is a function that adds default parameters to a function. In python, you can use functools. partial to generate a function's partial function. Take int () in python as an example. The int () function is converted in decimal by default. To generate a function that converts in octal, You can implement the following:

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

 

Summary

This article describes several basic concepts in functional programming. The most difficult thing to understand is the Decorator, especially the so-called configuration information. If any error occurs, please leave a message !!!

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.