[Python] exploring 'functional programming'

Source: Internet
Author: User
Tags php website
[Python] function programming

There was a course called 'artificial intelligence 'last semester. the teacher forced us to learn a language called prolog. wow, it was really uncomfortable, the way of thinking is completely different from what I have learned before. I 've been thinking about a tower for a long time, and finally I found some code on the Internet to modify it (for fear of being discovered by the teacher, post it and 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, I was almost familiar with it. The main reason was that there was too little information and debugging was impossible to talk about. when I encountered a bug, gg, and I felt a little dizzy now. However, it is said that prolog was able to compete with Lisp in the past and has recently become a bit interested in Lisp. after completing these steps, I will visit this type of functional language.

What is functional programming? Liao wrote:

Function programming is a programming paradigm with a high degree of abstraction. functions written in pure functional programming languages do not have Variables. Therefore, any function, as long as the input is definite, the output is definite. this pure function is called with no side effects. The programming language that allows the use of variables, because the variable state inside the function is not sure, the same input may have different outputs, so this function has side effects.

It may be hard to understand after reading these sections. Don't worry. read these sections first.

High-order functions

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

  • Accepts one or more functions as input.

  • Output a function

That is to say, 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 value assignment:

>>> min(1, 2)1>>> f = min>>> f(1, 2)1>>> f
 
  >>> min
  
 

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

>>> min = 10>>> min(1, 2)Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   TypeError: 'int' object is not callable>>> f(1, 2)1>>> min = f>>> min(1, 2)1
  
 

You can also pass parameters. for example, a function is used to calculate the sum of all 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, changing f to multiplication is the product of all numbers.

Let's take a look at some of python's built-in high-level functions, which are often used.

Map/reduce

I remember that I heard this word in the cloud computing course last semester. However, this course is very watery and I didn't hear much about it. it seems that it is not the same here ??

But I have nothing to say. let's briefly explain the role of each function.

For map, the formula is as follows:

map(f, [x1, x2, ..., xn]) = [f(x1), f(x2), ..., f(xn)]

For reduce, the formula is as follows:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

Liao has made it very clear.

Filter

Similar to the map function, filter accepts a function and iterable, and returns a list. However, the filter function determines whether to retain the value based on whether the return value of the function is True. For example:

Def is_odd (n): return n % 2 = 1 list (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # result: [1, 5, 9, 15]
Sorted

The sorted function is also a high-order function. the parameter key transfer function can sort the sequence to be sorted by the key function, but it does not change the value of the sequence. for example:

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

The anonymous function will not be mentioned. I will take a closer look at it later. I remember that I have been studying it for a long time before I saw flask. I will review it this time.

Simple decorator

The first is a simple decorator that prints the log before each function call:

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 ornament. how can we use it? The first use I saw was to add @ Before the function to be decorated, but it is actually a syntactic sugar of Python. The original usage is more understandable. first define a function f:

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

After this definition, we call the f function again:

>>> f()WARNING:root:f is runningin function f

The result of @ log is the same. In fact, the @ symbol is used as the syntactic sugar of the decorator and has the same function as the previous value assignment statement, making the code more concise and clear, avoid assigning values again, as shown below:

@logdef f():    print("in function f")
Decorator with parameters

Sometimes we also need to input parameters to the decorator, such as status and hierarchy. we only need to 'wrap 'a layer of functions outside the wrapper function, as shown below:

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 is running at level 2in function f
Further understanding

To further understand the decorator, we can print the name attribute of function f:

# For f without a decoration device, its name remains unchanged> def f ():... print ("in function f")...> f. _ name _ 'F' # The name of the function for adding the decorator is changed >>> @ log... def f ():... print ("in function f")...> f. _ name _ 'wrapper'

Contact the assignment statement at the beginning to get a general idea of what happened:f = log(f)So that f points to the return value modified to log (f), that is, the wrapper function. Each time the original function f is run, the wrapper function is called. In our example, the log is printed first and then the original function f is run.

However, there is a problem in this way, so that the meta information of the original function f is replaced, and a lot of information about f disappears, which is very unacceptable, but fortunately we have the functools module, modify the function:

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():...     print("in function f")...>>> f.__name__'f'

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

@ A @ B @ cdef f (): # equivalent to f = a (B (c (f )))
Summary

I am not very familiar with functional programming. here I just want to know about the concept of functional programming. at ordinary times, I must still use imperative programming. However, some languages are pure functional languages, such as Haskell or Lisp. learning them will give people a new idea.

For more articles about 'function programming 'in [python], please refer to the Chinese PHP website!

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.