Functional programming in Python

Source: Internet
Author: User
Tags definition bind range in python

Although Python is always used as a procedural, object-oriented language, he actually contains everything you need in functional programming. This article focuses on the general concept of functional programming and describes the technique of functional programming using Python.

We'd better start with the tough questions: "What exactly is functional programming?" "One of the answers may be this: functional programming is what you do when you use a language like Lisp (and Scheme,haskell,ml,ocaml,mercury,erlang and some other languages)." This is an insurance answer, but it doesn't explain clearly. Unfortunately for what is functional programming, it is difficult to have a coherent definition, even from the functional to the start itself, it is difficult to explain. This is like elephant. But it would be nice to get it done with imperative programming (imperative programming) (imperative programming is at least as much as you do with C,PASCAL,C++,JAVA,PERL,AWK,TCL and many other similar languages).

I have a rough summary of the idea that functional programming should at least have multiple features in the following points. It's easier to do this in a functional language, but it's not hard or impossible to do something else:

function has a primary position (object). That is, what you can do with "data" is something you can do with the function itself (such as passing a function as an argument to another function).

Recursion is used as the main control structure. In some functional languages, there is no other "looping" structure.

List processing as a focus (for example, the Lisp language name). Lists tend to replace loops by recursively substituting a list of subreports.

The "pure" functional language completely avoids side effects. This completely rejects the almost ubiquitous practice of imperative languages: assigning the first value to a variable to track the running state of the program, and then assigning another value to the same variable.

Functional programming does not discourage or completely prohibit the use of statements, but rather completes tasks by evaluation of an expression (in other words, a function plus arguments) (evaluation of expressions). In the purest case, a program is an expression (plus an auxiliary definition)

The most concern in functional programming is what to compute, not how to do it.

In many functional programming languages, the "High-order" (higher order) function is used (in other words, a high-order function is a function that operates on functions that perform operations on functions).

Advocates of functional programming believe that all these features help to write more concise and less bug-prone code faster. Furthermore, senior theorists in the three fields of computer science, logic and mathematics have found that the formal nature of functional programming languages and programs is much simpler to prove than imperative programming languages and programs.
The functional functions inherent in Python

Since Python 1.0, Python has had the most of the features listed above. But like most of the features Python has, these features appear in a language that blends a variety of features. And Python's OOP (object-oriented programming) feature is very much like, you want to use how much, the rest can be regardless of (until you need to use them until then). In Python 2.0, the very handy "syntax candy" is added to the list resolution (comprehensions). Although list resolution does not add any new features, it makes many old features look a lot better.

The basic elements of functional programming in Python include Functionsmap (), reduce (), filter (), and lambda operators (operator). In Python 1.x, the Apply () function can also be very handy for using a function's list return value directly for another function. Python 2.0 provides an improved syntax for this. It may be a bit surprising that using so few functions (and basic operators) is almost enough to write any Python program, and more specifically, it is almost unnecessary to execute Process control statements.

All (IF,ELIF,ELSE,ASSERT,TRY,EXCEPT,FINALLY,FOR,BREAK,CONTINUE,WHILE,DEF) can be handled in a functional programming style by simply using functions and operators in functional programming. Although it is really possible to completely exclude the use of all Process control commands in a program, it makes sense only if you want to participate in the "Python Chaos Programming" contest (which can write Python code very much like Lisp code). But it is valuable to understand how functional programming can be controlled by function and recursive expression flow control.
Eliminate Process Control statements

The first thing to consider in the elimination exercise is that, in fact, Python will "short-circuit" the Boolean expression evaluation. This provides us with an expression version of the If/elif/else branch statement (assuming that each branch calls only one function, and it is easy to organize it into a rescheduling when this is not the case).

Here's what to do:
Short-circuit a conditional call in Python


# Normal statement-based Flow control
If <cond1>: Func1 ()
Elif <cond2>: Func2 ()
ELSE:FUNC3 ()
05
# equivalent "Short circuit" expression
Modified (<cond1> and func1 ()) or (<cond2> and Func2 ()) or (Func3 ())
08
# Example "Short circuit" expression
Ten >>> x = 3
One >>> def PR (s): return s
>>> (X==1 and PR (' one ')) or (x==2 and PR (' two ')) or (Pr (' other '))
' Other '
>>> x = 2
>>> (X==1 and PR (' one ')) or (x==2 and PR (' two ')) or (Pr (' other '))
' Two '

The conditional invocation of our expression version might not seem like much of a trick; however, if we notice that the lambda operator must return an expression, this is even more interesting. Since, as we have shown, an expression can be judged by a short circuit that contains a condition, a lambda expression is a completely universal means of judging the return value of the expression condition. Let's take an example:

Short-circuiting Lambda in Python
>>> PR = lambda s:s
>>> namenum = lambda x: (X==1 and PR ("one") \
... or (x==2 and PR ("two")) \
... or (pr ("other"))
>>> Namenum (1)
' One '
Modified >>> Namenum (2)
' Two '
>>> Namenum (3)
' Other '

Take functions as the first-place objects

The previous example has shown that functions in Python are paramount, but somewhat tactful. When we create a function object with a lambda operation, what we get is completely generic. By its very nature, we can bind our objects to the "PR" and "Namenum" of the name, and in exactly the same way, we can also bind the number 23 or the string "spam" together with these names. However, just as we can directly use the number 23 (that is, it can be used as a function parameter) without binding it to any name, we can also use the function object we created using the lambda without having to bind it to any name. In Python, a function is another kind of value that we can sort of handle.

A lot of what we do with the most important objects is to pass them as arguments to the function map (), reduce (), and filter () that are intrinsic to functional programming. The first argument accepted by these three functions is a function object.

Map (), which corresponds to each item in one or more of the lists assigned to it, performs one function passed as a parameter to it, and finally returns a list of results.

Reduce () Executes the function passed to it as a parameter for each successor and the cumulative result of the final result, for example, reduce (lambda n,m:n*m, Range (1,10)) means "factorial of 10" (in other words, Multiply each item by the previous product

Filter () uses the function passed to it as a parameter to "evaluate" all items in a list, returning a selected list of all the items that can be tested by that function.

We often pass function objects to our own defined functions, but in general, these custom functions are some form of combination of the built-in functions mentioned above.

By combining these three functional programming built-in functions, you can implement an astonishing range of "execute process" operations (all without statements, only using an expression).
Functional loops 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.