Home >Backend Development >Python Tutorial >Let's analyze Python functional programming together

Let's analyze Python functional programming together

WBOY
WBOYforward
2022-03-03 17:27:551789browse

This article brings you relevant knowledge about python, which mainly introduces issues related to functional programming, that is, in the imperative paradigm, by providing the computer with a series of instructions and then Execute them to complete the task, hope it helps everyone.

Let's analyze Python functional programming together

Recommended learning: python learning tutorial

In this article, you will learn what functional paradigm is and how to use Python Do functional programming. You'll also learn about list comprehensions and other forms of comprehension.

Functional Paradigm

In the imperative paradigm, a task is accomplished by giving the computer a sequence of instructions and then executing them. When executing these instructions, certain states can be changed. For example, suppose you initially set A to 5 and then change the value of A. At this time, you change the state of A in the sense of the internal value of the variable.

In the functional paradigm, you don’t tell the computer what to do but tell it what it is. For example, what is the greatest common divisor of numbers, what is the product from 1 to n, etc.

Therefore, variables cannot change. Once you set a variable, it stays that way forever (note that in purely functional languages, they are not variables). Therefore, functional programming has no side effects. A side effect is when a function changes something other than itself. Let’s look at some examples of typical Python code:

The output of this code is 5. In the functional paradigm, mutating variables is a big no-no, and having functions that affect things outside of their scope is also a big no-no. The only thing a function can do is compute something and return it as a result.

Now you may be thinking: "No variables, no side effects? Why is this good?" This is a good question, I believe most people are confused about this.

If a function is called twice with the same parameters, it is guaranteed to return the same result. If you have studied mathematical functions, you will know the benefit. This is called referential transparency. Since functions have no side effects, if you are building a program that computes something, you can speed up the program. If func(2) returns 3 every time we call it, we can store it in a table, which prevents the program from running the same function repeatedly.

Normally, in functional programming, we don’t use loops. We use recursion. Recursion is a mathematical concept that usually means "calling itself." Use a recursive function that calls itself repeatedly as a subfunction. Here is a good example of a recursive function in Python:

Some programming languages ​​are also lazy. This means they don't calculate or do anything until the last second. If you write some code to do 2 2, the function program will only calculate it when you actually need to use the result. We'll explore laziness in Python soon.

Map

In order to understand, let’s first take a look at what iteration is. Typically objects that can be iterated over are lists or arrays, but Python has many different types that can be iterated over. You can even create your own objects that can be iterated over by implementing magic methods. Magic methods are like an API that help your objects become more Pythonic. You need to implement 2 magic methods to make the object iterable:

The first magic method "__iter__" (note: double underscore here) returns the iterable object, This is usually used at the beginning of a loop. "__next__" returns the next object.

Let us quickly enter a terminal and call the above code:

Running will print out

In Python, an iterator is an object with only __iter__ magic method. This means you can access locations within an object, but you cannot traverse the object. Some objects will have the magic method __next__ instead of the __iter__ magic method, such as collections (discussed later in this article). For this article, we'll assume that everything we touch is an iterable object.

Now that we know what an iterable object is, let's go back to the map function. The map function allows us to apply a function to each item in the iterable. Map requires 2 inputs, which are the function to be applied and the iterable object.

Suppose we have a list of numbers as follows:

We want to square each number, we can write the following code:

Functional functions in Python are lazy. If we don't use "list", the function will store the definition of iterable instead of the list itself. We need to explicitly tell Python to "turn this into a list" for us to use.

It's a bit strange to suddenly switch from non-lazy to lazy evaluation in Python. If you think more in a functional way of thinking rather than an imperative way of thinking, you'll eventually get used to it.

Now writing a normal function like "square(num)" is nice, but it's not right. Do we have to define a complete function to use it in map? Well, we can define a function in map using lambda (anonymous) function.

Lambda expression

A lambda expression is a function with only one line. For example, this lambda expression squares a given number:

Let’s run it:

Doesn't this look like a function?

Well, this is a bit confusing, but explainable. We assign something to the variable "square". What about this one:

# Tell Python that this is a lambda function and the input is called x. Anything after the colon is what you do with the input and it automatically returns the result.

Simplifying our square program to only one line of code, we can do this:

So in the lambda expression, all the parameters are on the left, you The stuff you want to make with them is on the right. It's a bit messy. But the truth is, there's a certain amount of fun in writing code that only other functional programmers can read. Also, it's pretty cool to take a function and turn it into a line of code.

Reduce

Reduce is a function that turns an iteration into one thing. Typically, you use the reduce function on a list to perform calculations to reduce it to a number. Reduce looks like this:

#We often use lambda expressions as functions.

The product of a list is the multiplication of each individual number. To do this you would write code like this:

But using reduce you can write like this:

to get Same functionality, code is shorter and cleaner using functional programming. (Note: The reduce function is no longer a built-in function in Python3 and needs to be imported from the functools module)

Filter

The filter function adopts an iterable method and filters out Everything you don't need in that iterable.

Usually, filter requires a function and a list. It applies a function to each item in the list and does nothing if the function returns True. If False is returned, the item is removed from the list.

The syntax is as follows:

Let us look at a small example, without filter we would write:

Using filter, you can write like this:

As a language that is constantly developing and popularizing, Python is still being updated. When studying, it is recommended to find some study partners to study and discuss together for better results. If you want to learn Python, you are welcome to join the Python learning exchange group (627012464) to supervise and learn together. It contains development tools, a lot of useful information and technical information to share!

Higher-order functions

Higher-order functions can take functions as parameters and return functions. A very simple example is as follows:

The second example of returning a function:

I said at the beginning that pure Functional programming languages ​​have no variables. Higher order functions make this easier.

All functions in Python are first-class citizens. A first-class citizen is defined as having one or more of the following characteristics:

Created at runtime

Assigned a variable or element in a data structure

Passed as an argument to a function

Returned as the result of a function

All functions in Python can be used as higher-order functions.

Partial application

Partial application (also known as closure) is a bit weird, but very cool. You can call a function without providing all the required parameters. Let's see this in an example. We want to create a function that takes 2 arguments, a base and an exponent, and returns the base raised to the power of the exponent like this:

Now we want a A dedicated square function that finds the square of a number using the power function:

This works, but what if we want a cube function? Or what about finding the function of the fourth power? Can we keep writing about them? Well, you can. But programmers are lazy. If you're repeating the same thing over and over again, it's a sign that there's a faster way to speed things up that will keep you from repeating it. We can use closures here. Let’s look at an example of the square function using closures:

# Isn’t that cool! We can call a function that requires 2 parameters with only 1 parameter.

We can also use a loop to generate a power function that implements powers from the cube all the way up to 1000.

Functional programming is not pythonic

You may have noticed that many of the things we want to do in functional programming It's all about lists. With the exception of reduce functions and closures, all the functions you see generate lists. Guido (the father of Python) didn't like functional expressions in Python because Python already had its own way of generating lists.

If you write "import this" in Python's interactive environment, you will get:

This is the Zen of Python. This is a poem about what it means to be Pythonic. The part we want to cover is:

There should be one — and preferably only one — obvious way to do it. (should try to find one, preferably only one obvious solution)

In Python, map and filter can perform the same operations as list comprehensions (discussed below). This breaks one of the rules of the Zen of Python, so these parts of functional programming are not considered "pythonic".

Another topic is Lambda. In Python, a lambda function is a normal function. Lambda is syntactic sugar. These two statements are equivalent.

A normal function can do everything a lambda function can do, but it cannot work the other way around. Lambda functions cannot do everything that normal functions can do.

This is a brief argument why functional programming does not fit well into the overall Python ecosystem. You may have noticed that I mentioned list comprehensions earlier and we will discuss them now.

List comprehension

Earlier, I mentioned that anything you can do with map or filter, you can use list comprehension. List comprehension is a way to generate lists in Python. The syntax is:

Let’s square each number in the list, for example:

We can see to how to apply a function to each item in a list. How do we apply filter? Look at the previous code:

We can convert it into a list comprehension, like this:

List Supports statements like if. You no longer have to apply a million functions to something to get what you want. In fact, if you want to try to generate some kind of list, it seems cleaner and easier to use a list comprehension. What if we wanted to square every number below 0 in the list? With lambda, map and filter you would write:

This seems very long and complicated. With a list comprehension, it's just:

List comprehensions only work with lists. map and filter are suitable for any iterable object, so what is the use of this? You can use any deduction on any iterable object you encounter.

Other derivation

You can create a derivation for any iterable object.

Any iterable object can be generated using derivation. Starting with Python 2.7, you can even generate dictionaries (hashmaps).

If it is iterable, it can be generated. Let's look at the last set of examples.

set is a list of elements in which no element is repeated twice.

The elements in set have no order.

You may notice that set has the same curly braces as dict. Python is very smart. Depending on whether you provide a value for the dict, it will know whether you are writing a dict deduction or a set deduction.

Recommended learning: python tutorial

The above is the detailed content of Let's analyze Python functional programming together. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete