[Python] Preliminary discussion on ' functional programming '

Source: Internet
Author: User

Function-Type programming

Last semester there is a class called ' Artificial intelligence ', the teacher forced us to learn a language called Prolog, wow that feeling is really uncomfortable, the way of thinking completely and previously learned not the same, write a Hanoi thought for a long time, finally or on the Internet to find a paragraph code modification (afraid of the teacher found plagiarism) just write out, Post a paragraph to feel it:

Hanoi (N):-Dohanoi (N, ' a ', ' B ', ' C '). Dohanoi (0, _, _, _)    :-!. Dohanoi (n, A, B, C)    :-  N1 is N-1,  Dohanoi (N1, A, C, B),  writeln ([Move, N, A-->c]),   Dohanoi (N1, B, A , C).

At that time is almost understand, mainly is too little information, debug can not talk about, a bug on the GG, I now see also a little dizzy. But it is said that Prolog was able to compete with Lisp, recently a little interest in Lisp, and so on to visit this kind of functional language.

What is functional programming? Liao da wrote here:

Functional programming is a very high degree of abstraction of the programming paradigm, the purely functional programming language functions are not variable, so any function, as long as the input is determined, the output is OK, this pure function we call no side effects. In the case of programming languages that allow the use of variables, because of the variable state inside the function, the same input may get different output, so this function has side effects.

Maybe after reading or some do not understand, do not hurry, read these several bars first.

Higher order functions

In mathematics and computer science, higher-order functions are functions that meet at least one of the following conditions:

    • Accept one or more functions as input

    • Output a function

In other words, the function itself is passed as a parameter, or a function is returned.

For example, you can assign a function to a variable like a normal assignment:

>>> min (1, 2) 1>>> F = min>>> f (1, 2) 1>>> f<built-in function min>>>> m in<built-in function min>

You can also assign a value to a function (the code is connected):

>>> min = 10>>> min (1, 2) Traceback (most recent):  File "<stdin>", line 1, in <mod Ule>typeerror: ' int ' object is not callable>>> f (1, 2) 1>>> min = f>>> min (1, 2) 1

You can also pass a parameter, for example, a function that calculates all the numbers:

>>> def add (A, B): ...     Return a+b...>>> def mysum (F, *l): ...     A = 0     ... For i in L: ...             A = f (A, i)     ... Return a...>>> mysum (Add, 1, 2, 3) 6>>> mysum (Add, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 55

Of course, converting this f to multiplication is the product of all numbers.

Take a look at some of the higher-order functions built into Python, which are often used.

Map/reduce

Remember last semester in the cloud computing course, vaguely heard the word, but this lesson is very water, did not listen to, see here as if found not quite the same??

But there's nothing to say, just a brief look at the function of each.

For map, the formula can be seen as:

Map (f, [X1, x2, ..., xn]) = [F (x1), F (x2), ..., f (xn)]

For reduce, the formula can be seen as:

Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)

Liao There was a clear word.

Filter

The filter, like the map function, accepts a function and iterable, and returns a list, but its function is to determine whether the value is preserved based on whether the function returns a value of True. For example:

def is_odd (n):    return n% 2 = = 1list (Filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # results: [1, 5, 9, 15]

Sorted

The sorted function is also a high-order function, and the parameter key transfer function can then sort the sequences that need to be arranged through the key function, but does not change the value of the sequence, for example:

>>> sorted ([5, -12, 9, -21], key=abs) [5, 9,-12,-21, 36]

Adorner (decorator)

Anonymous function will not say, later time to look carefully, decorator I remember before looking at flask when all studied for a long, this time again to review.

Simple decorator

The first is a simple adorner that prints out the log before each call to the function:

Import loggingdef Log (func):    def wrapper (*args, **kw):        Logging.warn ("%s is running"% func.__name__)        func ( *args, **kw)    return wrapper

This is an extremely simple adorner, how to use it? The first thing I see is to add @ before the function that needs to be decorated, but it's actually a syntax sugar for Python, and the primitive usage is more understandable, first defining a function f:

def f ():    print ("in function f") F = log (f)

After this is defined, we call the F function again:

>>> f () Warning:root:f is Runningin function f

The result of using the @log is the same as the syntax sugar of the @ symbol as the adorner, which has the same function as the previous assignment statement, making the code look more concise and avoid assigning operations again, as follows:

@logdef f ():    print ("in function f")

Adorner with parameters

Sometimes we also need to pass in parameters such as status, hierarchy, etc. to the adorner, just to ' wrap ' a layer of functions outside the wrapper function as follows:

Import Loggingdef log (level):    def Decorator (func):        def wrapper (*args, **kw):            Logging.warn ("%s is running At level%d "% (func.__name__, level))            return func (*args, **kw)        return wrapper    return Decorator@log (2) def f ( ):    print ("in function f")    >>> F () Warning:root:f are running at level 2in function f

Further understanding

To further understand the adorner, we can print out the Name property of the function f:

#对于不加装饰器的 F, its name is constant >>> def f ():     ... Print ("in function f") ...>>> f.__name__ ' F ' #对于添加装饰器的函数, whose name changed >>> @log ... def f ():     ... Print ("in function f") ...>>> f.__name__ ' wrapper '

By contacting the front-most adorner assignment, you can roughly understand what happened: f = log(f) make F point to the return value of log (f), which is the wrapper function. Each time the original function f is run, the wrapper function is called, in our case, the log is printed first and then the original function f is run.

However, there is a problem, so that the original function f of the meta-information is replaced, about f a lot of information disappears, it is very difficult to accept, but fortunately we have the Functools module, modify the function as:

Import functoolsimport loggingdef log (func):    functools.wraps (func)    def wrapper (*args, **kw):        Logging.warn ("%s is running"% func.__name__)        func (*args, **kw)    return wrapper>>> @log ... def f (): ... C6/>print ("in function f") ...>>> f.__name__ ' F '

In addition, you can add multiple adorners to the same function:

@a@b@cdef f (): # equivalent to f = a (b (C (f)))

Summarize

About functional programming I do not know very well, here is just about the concept of it, usually certainly still use command-style programming more. But language is a purely functional language, such as Haskell or Lisp, and learning them can open up a new way of thinking.

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.