Functional programming in Python

Source: Internet
Author: User

One feature of functional programming is that it allows
1. Pass the function itself as a parameter to another function!
2. return a Function!
Python mainly has the following functional programming methods, which are described in terms of concepts , functions , and sample code .

      • A high-order function function as a parameter
        • Map and reduce
        • Filter filters
      • Two how to return a function
        • Lambda expression anonymous method
        • Decorative Device
        • Partial function

I. Higher-order functions (functions as parameters)

This actually corresponds to the first feature, that "the function itself as a parameter into another function", similar to C + + "function pointer", such a technique is easy to implement template technology, the most commonly used is the sort function, see the following code, The sort in Python is the default from small to large for int types, if we want to customize the order? This time the power of the "higher order function" manifests itself.

#!usr/bin/env pythonimport mathL = [0, -1820, -99]print sort(L, abs)

As shown above, the ABS function is passed into sort as a parameter as an argument, why is it possible? In fact, the function name of the ABS function is used as the parameter, in Python, a well-defined parameter is actually a variable stored in memory, such as the following interaction :

>>> def fun():...     print‘haha‘... >>> 0x7faf4667f578>>>>

The specific address is probably not the same as I printed, but the essence is the same address, which also verifies the above "function name is a variable" argument.

1. Map and reduce

These two built-in functions are classic examples of high-order function applications, and look directly at the sample code:

#!usr/bin/env pythondef lala(x, y=2015):    return x % yprint map(lala, range(20002030)

The result of the operation is:[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

#!usr/bin/env pythondef plus(x, y):    return x * yprint reduce(plus, range(15))

The result is: 24 1*2*3*4
In fact, from the above code and run the results can be guessed that the role of the two functions exactly what, they all accept two parameters. The first one is a function name , the second is a list , and map takes each element of the list as an argument Returns a list of return values for each function, paying attention to the number of arguments passed in the function, and if more than one is required, the corresponding list will be changed.
As for reduce, the requirements for incoming functions are stricter and need to be exactly an even number (with default parameters not included), because what it does is to sequentially execute from the list, and then pass the last execution of the return value to the next element in the list to calculate, the above code is equivalent to

a = plus(12)  #首先是取第1,第2个元素b = plus(a3)  #然后返回值作为第一个参数,取下一个元素做为第二个参数4)  #同上print c

What is the function of such a two function? can only provide a little grammer sweet ? The answer is NO!!! For more details, see Niang.
I think the meaning of the sentence is "it greatly facilitates the programmer to run their own program on a distributed system without distributed parallel programming."

2. Filter filters

As the name implies, the filter is based on the rules you provide to keep the required data, filter also accepts two parameters, the first one is a return Boolean function, the second is an element type is a list of parameters of the Boolean function. Look at the sample code first:

#!usr/bin/env pythonImportMath def is_prime(n):    ifN <=1:return False     forIinchRange2, (int) (MATH.SQRT (n) +1)):ifn% i = =0:return False    return TruePrintFilter (Is_prime, Range (1,101))

The result is: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
That is, 1 to 100 of all primes.

Two. How to return a function 1. Lambda expression (anonymous method)

Simple lambda expressions are supported in Python, such as:

>>> lambda x : x * x>>> f<function <lambda0x7faf4667fb18>>>>

At a glance, yes, it is used to generate anonymous methods!

"... lambda expressions and anonymous methods is really just the words for the same thing. The only thing that differs was, "What's does the syntax look like" and the lambda expressions was a further evolution of th e syntax. But underneath, they does the same thing. They generate methods. You know, they ' re in-line methods.
--c# chief architect Anders Hejlsberg

This leads to the concept of a closure , how does it return a function? or look at the code directly:

#!usr/bin/env pythondef f(x):    def fun():        return x * x    return fun>>> f(1).__name__‘fun‘>>> 

See here it should be clear, using closures, we can directly use the parameters of the function to save the current function call scene!!! As for what use, on a matter of opinion, use, nature will understand the beauty of it, but I still do not know t_t.

2. Decorative Device

The anonymous method above returns "native function content", so what if you want to add functionality to the function without changing the source code? There is no way, the decorator was born ... Use the code directly to know:

#!usr/bin/env python def log(func):     def haha(*args, **kw):        Print ' Call%s (): '% func.__name__returnFunc (*args, **kw)returnhaha@log def now(x):    Print ' wo Cao,%s '% x>>>Now' 12 o '.) Call Now (): Wo Cao, APoint of >>>

Using the @ syntax, the log is used to decorate the now function. The log function is actually the "closure" mentioned above. This simply adds a "pre-call declaration" to the function, and it's a similar way to add something else.
It is worth noting that:
A) "the Principle of decoration "
@log can actually be seen as something like this: now = log, which means that the existing now function is overwritten and becomes a function that has been decorated with a log closure.
b) function parameter???
This uses the "Universal parameter List":(*args, **kw), which means that whatever the parameter list of the function you need to modify, it can be modified!
More detailed explanation see Liao Big (LDD).

3. Partial function

In fact, this name is from the snow-capped big tutorial there, feeling a bit literal translation, but the discrete mathematics inside the partial order seems to be so literal, it does not struggle with the naming problem. What's the function of this return?

When a function has too many arguments and needs to be simplified, use functools.partial to create a new function that can fix some of the parameters of the original function, making it easier to invoke.
--from LDD

See a simple example to understand:

#!usr/bin/env pythonimport functools    #注意要import这个模块#example code is from LDDint2 = functools.partial(int, base=2)>>> import functools>>> int2 = functools.partial(int, base=2)>>> int2(‘1000000‘)64>>> int2(‘1010101‘)85

The binary is converted to decimal, fixed the value of the parameter base, relative to the "full", called "biased" is also very intuitive!

At this point, the two main aspects of functional programming in Python have been briefly described. Thank you.
Read ~ Break sleep (⊙o⊙)!

Functional programming in 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.