In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail what Python functional programming is. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Function paradigm
In the imperative paradigm, a task is accomplished by providing a series of instructions to the computer and then executing them. Some states can be changed when these instructions are executed. For example, suppose you initially set A to 5, and then change the value of A. Then, in the sense of the internal value of the variable, you change the state of A.
In the functional paradigm, you don't tell the computer what to do, you tell him what it is. For example, what is the greatest common divisor of a number, what is the product from 1 to n, and so on.
Therefore, the variable cannot be changed. Once you set a variable, it stays in this state forever (note that in a purely functional language, they are not variables). Therefore, functional programming has no side effects. The side effect is that the 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, changing variables is a big taboo, and it is also a big taboo to have the function of affecting things outside its scope. The only thing a function can do is calculate something and return it as a result.
Now you might think, "No variables, no side effects? why is that good?" That's a good question, and I'm sure most people are confused about it.
If the function is called twice with the same argument, the same result is guaranteed to be returned. If you have learned mathematical functions, you will know this benefit. This is called reference transparency. Since functions have no side effects, if you are building a program that calculates something, you can speed up the program. If we return 3 for every call to func (2), we can store it in the table, which prevents the program from running the same function repeatedly.
In general, in functional programming, we do not use loops. We use recursion. Recursion is a mathematical concept that usually means "self-invocation". Use a recursive function, which repeatedly calls itself as a subfunction. This is a good example of a recursive function in Python:
Some programming languages are also lazy. This means that they don't calculate or do anything until the last second. If you write some code to execute 2 + 2, the function program will only calculate it when you really need to use the result. We will soon explore inertia in Python.
Map
To understand, let's first look at what iteration is. Usually the objects that can iterate are lists or arrays, but Python has many different types to iterate over. You can even create your own objects that can be iterated by implementing magic methods. The magic method is like an API that can help your object become more Pythonic. You need to implement two magic methods to make the object iterable:
The first magic method "_ _ iter__" (note: here is a double underscore) returns an iterative object, which is usually used at the beginning of the loop. "_ _ next__" returns the next object.
Let's quickly enter a terminal to call the above code:
The run will print out
In Python, an iterator is an object with only _ _ iter__ magic methods. This means that you can access the location in the object, but you cannot traverse the object. Some objects will have magic methods _ _ next__ instead of _ _ iter__ magic methods, such as collections (discussed later in this article). For this article, we assume that everything we come into contact with 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 the function to every item in the iterable. Map requires two inputs, which are the function to be applied and the iterable object.
Suppose we have a list of numbers, as follows:
If we want to square each number, we can write the following code:
Functional functions in Python are lazy. If we do not use "list", this function will store the definition of the iterable, not the list itself. We need to explicitly tell Python to "turn it into a list" for us to use.
It's a bit strange to suddenly switch from non-lazy evaluation to lazy evaluation in Python. If you think more about the functional way of thinking than the imperative way of thinking, you will eventually get used to it.
It's nice to write an ordinary function like "square (num)" now, but it's not right. Do we have to define a complete function to use it in map? Well, we can use the lambda (anonymous) function to define a function in map.
Lambda expression
The 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, it's a little confusing, but it can be explained. We assign something to the variable "square". What about this:
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.
To simplify 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, and what you're going to do with them is on the right. It's a little messy. But the truth is, it's fun to write code that only other functional programmers can read. In addition, it's cool to use a function and convert it to a single line of code.
Reduce
Reduce is a function that turns iteration into something. Typically, you can use the reduce function on the list to perform calculations to reduce it to a number. Reduce looks like this:
We often use lambda expressions as functions.
The product of the list is the multiplication of each individual number. To do this, you will write the following code:
But with reduce, you can write:
Get the same functionality, have shorter code, and be cleaner when 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 takes an iterable approach and filters out everything you don't need in that iterator.
Typically, filter requires a function and a list. It applies the 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's look at a small example. Without filter, we would write:
Using filter, you can write:
As a developing and popularized language, Python is still being updated. In learning, it is recommended to find some learning partners to study and discuss together, the effect is better. If you want to learn Python, welcome to join the Python Learning Exchange Group (627012464), supervise and study together. There are development tools, a lot of practical information and technical information to share!
Higher order function
Higher-order functions can take a function as an argument and return a function. A very simple example is as follows:
The second example of a return 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. First-class citizens are defined as having one or more of the following characteristics:
Create at run time
Assign variables or elements in a data structure
Passed as a parameter of 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 closures) is a little weird, but very cool. You can call the function without providing all the required parameters. Let's see this in an example. We want to create a function that takes two parameters, a cardinality and an exponent, and returns the cardinality of the exponential power, as follows:
Now we want a special square function, using the power function to calculate the square of the number:
It works, but what if we want a cube function? Or ask for the function of the fourth power? Can we continue to write them down? Okay, you can. But programmers are lazy. If you repeat the same thing over and over again, it shows that there is a faster way to speed up, which will prevent you from repeating it. We can use closures here. Let's look at an example of a square function that uses closures:
Isn't that cool! We can use only one argument to call a function that requires two arguments.
We can also use a loop to generate a power function that goes from the cube to the power of 1000.
Functional programming is not pythonic
You may have noticed that many of the things we want to do in functional programming revolve around lists. With the exception of reduce functions and closures, all the functions you see generate lists. Guido (the father of Python) doesn't like functions in Python because Python already has its own way of generating lists.
If you write "import this" in the interactive environment of Python, you will get:
This is the Zen of Python. This is a poem about what Pythonic means. The part that we want to cover is:
There should be one-and preferably only one-obvious way to do it. (try to find one, preferably the only obvious solution.)
In Python, map and filter can perform the same operation as list derivation (discussed below). This breaks a rule of the Zen of Python, so these parts of functional programming are not considered "pythonic".
Another topic is Lambda. In Python, the lambda function is a normal function. Lambda is a grammatical sugar. These two statements are equivalent.
A normal function can do everything the lambda function can do, but it cannot work in the opposite way. The lambda function does not do everything that a normal function can do.
This is a brief demonstration of why functional programming doesn't work well for the entire Python ecosystem. You may have noticed that I mentioned list derivation earlier, and we will discuss them now.
List derivation
Earlier, I mentioned anything you can do with map or filter, you can use list derivation. List derivation is a way to generate lists in Python. The syntax is:
Let's square each number in the list, for example:
We can see how to apply the function to each item in the list. How do we apply filter? Take a look at the previous code:
We can convert it into a list derivation, like this:
Lists support statements like if. You no longer need 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, using list derivation looks clearer and easier. What if we want to square every number below zero in the list? With lambda,map and filter, you can write:
It seems very long and complicated. Through the list derivation, it is just:
List derivation applies only to lists. Map,filter fits any object that can be iterated over, so what's the use of that? You can use any derivation for any iterable object you encounter.
Other deductions
You can create a derivation for any iterable object.
You can use derivation to generate any iterable object. Starting with Python 2.7, you can even generate dictionaries (hashmap).
If it is iterable, it can be generated. Let's take a look at the example of the last group.
Set is a list of elements in which no element is repeated twice.
The elements in set are out of order.
You may notice that set (collection) and dict (dictionary) have the same curly braces. Python is very clever. Depending on whether you provide a value for dict, it will know whether you are writing a dict derivation or an set derivation.
This is the end of this article on "what is Python functional programming". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.