12. Functional Programming

Source: Internet
Author: User

function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design.

and functional programming (note that more than one "type" word)--functional programming, although it can also be attributed to the process-oriented programming, but the idea is closer to the mathematical calculation.

We first have to understand the concepts of computer (computer) and computational (Compute).

At the level of the computer, the CPU executes the subtraction instruction code, as well as various conditional judgments and jump instructions, so, assembly language is the most close to the computer languages.

And the calculation of the exponential meaning, the more abstract calculation, the farther away from the computer hardware.

corresponding to the programming language, is the lower level of the language, the more close to the computer, low degree of abstraction, implementation of high efficiency, such as C language, the more advanced language, the more close to the computation, high degree of abstraction, inefficient execution, such as Lisp language.

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.

One of the features of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows a function to be returned!

Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

Higher order functions

Higher-order functions are called Higher-order function in English. What is a higher order function? We take the actual code as an example, step by step in-depth concept.

Variables can point to functions

For example, in Python's built-in function for absolute values abs() , call the function with the following code:

# Coding=utf-8   Print ABS (-10)

But what if it was written only abs ?

>>> ABS<built- in function abs>

Visible, abs(-10) is the function call, but abs the function itself.

To get the result of a function call, we can assign the result to the variable:

>>> x = ABS ( -10)>>> x10

But what if the function itself is assigned to a variable?

>>> f = abs>>> f<built- in function abs>

Conclusion: The function itself can also be assigned to the variable, that is: The variable can point to the function.

If a variable points to a function, can it be called by this variable? Verify with code:

The function name is also a variable

So what is the function name? The function name is actually a variable pointing to the function! For abs() This function, it is perfectly possible to think of a function name as abs a variable, which points to an absolute value!

What happens if you abs point to a different object

>>> ABS = 10>>> ABS ( -10) Traceback (most recent)  :"<stdin>< /c6>" in <module>'int'are not callable

absafter the pointer 10 is pointed, it cannot be abs(-10) called by the function! Because abs this variable does not point to an absolute value function but points to an integer 10 !

Of course, the actual code must not be written like this, this is to illustrate the function name is also a variable. To restore abs The function, restart the Python interactive environment.

Note: Since the abs function is actually defined in import builtins the module, it is needed to make the pointer to the modified abs variable take effect in other modules as well import builtins; builtins.abs = 10 .

Incoming function

Since the variable can point to a function, the function's arguments can receive the variable, then one function can receive another function as a parameter, which is called the higher order function.

One of the simplest high-order functions:

When we call add(-5, 6, abs) , Parameters x , y and f respectively receive -5 , 6 and, according to the abs function definition, we can deduce the calculation process as:

# Coding=utf-8   def Add (x, Y, f):     return f (x) + f (y)print Add ( -5,6,abs)

Writing higher-order functions allows the parameters of a function to receive other functions.

Map/reduce

Python has built map() -in and reduce() functions.

If you read Google's famous paper "Mapreduce:simplified Data processing on Large Clusters", you can probably understand the concept of map/reduce.

Let's look at map first. The map() function receives two arguments, one is the function, the other is to function the Iterable map incoming function to each element of the sequence sequentially, and returns the result as a new one Iterator .

For example, we have a function f (x) =x2, to function on a list [1, 2, 3, 4, 5, 6, 7, 8, 9] , it can be map() implemented as follows:

\

Now, we use Python code to implement:

# Coding=utf-8   def f (x):     return x *= map (f,[1, 2, 3, 4, 5, 6, 7, 8, 9])print list (R)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

map()The first parameter passed in is the f function object itself. Since the result r is one Iterator , it is an Iterator inert sequence, so the list() function allows it to calculate the entire sequence and return a list.

You might think that you don't need map() a function, write a loop, or you can calculate the result:

# Coding=utf-8   L = []def  F (x):     return x * x for in [1, 2, 3, 4, 5, 6, 7, 8, 9]:    l.append (f (n))print(L)

Yes, but, from the loop code above, can you see "putting F (x) in every element of the list and generating a new list"?

So, map() as a higher-order function, in fact it abstracts the arithmetic rules, so we can not only calculate the simple f (x) =x2, but also can calculate any complex function, for example, the list of all the numbers into a string:

Yes, but, from the loop code above, can you see "putting F (x) in every element of the list and generating a new list"?

So, map() as a higher-order function, in fact it abstracts the arithmetic rules, so we can not only calculate the simple f (x) =x2, but also can calculate any complex function, for example, the list of all the numbers into a string:

# Coding=utf-8   Print list (map (str,[1,2,3,4,5,6,7,8,9))

Only one line of code is required.

Again look at reduce the usage. To function reduce on a sequence [x1, x2, x3, ...] , the function must receive two parameters, reduce and the result continues and the next element of the sequence is accumulated, the effect is:

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

For example, to sum a sequence, it can be reduce implemented by:

# Coding=utf-8    from Import Reduce def f (x):     return x * xdef  Add (x, y    ):return x + yPrint reduce (add,[1,3,5,7,9])
25

Of course, the sum operation can be directly built into Python functions sum() , no need to use reduce .

But if you want to [1, 3, 5, 7, 9] transform the sequence into integers 13579 , you can put reduce it in handy:

 from Import Reduce def f (x):     return x * xdef  Add (x, y    ):return x + ydef fn (x, y    ): return x * + yprint reduce (fn,[1,3,5,7,9])
13579

This example is not very useful in itself, but if we consider that the string str is also a sequence, with a slight change to the above example, map() we can write the str converted int function:

>>> fromFunctoolsImportReduce>>>deffn (x, y): ...returnX * 10 +y ...>>>defChar2num (s): ...return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s] ...>>> reduce (FN, map (Char2num,'13579'))13579

str2intthe function that is organized into one is

 fromFunctoolsImportReducedefStr2Int (s):deffn (x, y):returnX * 10 +ydefChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s]returnReduce (FN, map (Char2num, s))

You can also use lambda functions to further simplify:

 fromFunctoolsImportReducedefChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s]defStr2Int (s):returnReduceLambdaX, y:x * + y, map (Char2num, s))

You can also use the lambda function to further simplify into: the back of the fine study, do not do a demonstration here, in fact, do not know AH

Practice

1. Using the map() function, the user entered the non-standard English name, the first letter capitalized, the other lowercase canonical name. Input: [‘adam‘, ‘LISA‘, ‘barT‘] , output: [‘Adam‘, ‘Lisa‘, ‘Bart‘] :

#Coding=utf-8 fromFunctoolsImportReducedefNormalize (name):returnname.capitalize () L1= ['Adam','LISA','BarT']l2=list (map (NORMALIZE,L1))Print 'L2', L2

Small summary: The test capitalize () is a string method, you can capitalize the first letter of the string, the rest of the letter lowercase!,map2 parameters, functions, queues, the parameters of the calling function will be each value in the queue, separate to remove the function

2.Python provides a sum() function that accepts a list and sums it, write a prod() function that accepts a list and uses the quadrature reduce() :

# Coding=utf-8    from Import Reduce def prod (x, y    ): return x *= [3, 5, 7, 9]print reduce (prod,l)

To summarize, reduce has 2 parameters, (called function, sequence), the called function should have 2 parameters--example is the whole sequence, do not understand yes, and then again--, 2 parameters corresponding to the sequence of sequential variables

12. Functional Programming

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.