程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Teach you Python functional programming hand in hand

編輯:Python

In this article , You'll learn what functional paradigms are and how to use them Python Do functional programming . You'll also learn about list derivation and other forms of derivation .

Function normal form

In imperative paradigm , By providing the computer with a series of instructions and then executing them to complete the task . In executing these instructions , You can change certain states . for example , Suppose you're going to A Set to 5, And change the A Value . In the sense of the internal value of the variable , You've changed A The state of .

In the functional paradigm , You don't have to tell the computer what to do, but what it is . For example, what is the greatest common divisor of a number , from 1 To n And so on .

therefore , Variables can't change . Once you set a variable , It's always in this state ( Be careful , In pure functional languages , They're not variables ). therefore , Functional programming has no side effects . Side effects are when a function changes something other than itself . Let's look at some typical Python Examples of 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 influencing things beyond its scope . The only thing a function can do is compute something and return it as a result .

Now you might think :“ No variables , No side effects ? Why is it so good ?“ That's a good question , I believe most people are confused about this .

If you call the function twice with the same parameters , The same result is guaranteed . If you've learned mathematical functions , You'll know the benefit . This is called reference transparency . Because the function has no side effects , If you're building a program to calculate something , You can speed up the program . If you call func(2) All back to 3, We can store it in a table , This prevents the program from running the same function repeatedly .

Usually , In functional programming , We don't use loops . We use recursion . Recursion is a mathematical concept , Usually it means “ Self calling ”. Using recursive functions , The function repeats itself as a child function . This is a Python A good example of recursive function in :

Some programming languages also have inertia . That means they don't calculate or do anything until the last second . If you write some code to execute it 2 + 2, Function programs only work out when you really need to use the results . We will be in soon Python Explore inertia in the world .

Map

In order to understand , Let's first look at what iteration is . Usually the objects that can be iterated are lists or arrays , but Python There are many different types that can be iterated . You can even create your own objects , These objects can be iterated by implementing magic methods . The magic method is like a API, Can help your object become more Pythonic. You need to implement 2 There's a magic way to make an object iterative :

The first magic method “\_\_iter\_\_”( notes : Here's the double underline ) Return iteration object , This is usually used at the beginning of the loop .”\_\_next\_\_“ Return to the next object .

Let's quickly go to a terminal and call the code above :

The run will print out

stay Python in , An iterator is just a \_\_iter\_\_ The object of the magic method . This means that you can access the location in the object , But you can't traverse the object . Some objects will have magic methods \_\_next\_\_ instead of \_\_iter\_\_ Magic methods , For example, assemble ( We will discuss later in this article ). For this article , Let's assume that everything we touch is an iterative object .

Now we know what an iteratable object is , Let's go back to map function . map Functions allow us to apply functions to iterable Every one of them . Map need 2 Inputs , They are the function to be applied and the iteratable object .

Suppose we have a list of numbers , As shown below :

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

Python The function of the functional expression in is inert . If we don't use “list”, This function will store iterable The definition of , Not the list itself . We need to be clear about Python“ Turn it into a list ” For our use .

stay Python It's a bit strange to suddenly shift from non inert evaluation to inert evaluation in . If you think more about functional thinking , Not imperative thinking , So you'll get used to it in the end .

Now write a picture “square(num)” This kind of ordinary function is very good , But it's not right . We have to define a complete function in order to map Use it in ? ok , We can use lambda( anonymous ) Function in map Define a function in .

Lambda expression

lambda An expression is a function with only one line . for instance , This lambda The expression squares a given number :

Let's run it :

Doesn't that look like a function ?

Um. , It's a little confusing , But it can explain . We assign something to variables “square”. What about this one :

tell Python This is a lambda function , The input is called x. Anything after the colon is what you do with the input , It will automatically return results .

Simplify our square The program has only one line of code , We can do that :

So in lambda Expression , All the parameters are on the left , What you're going to do with them is on the right . It's a bit messy . But the truth is , It's fun to write code that only other functional programmers can read . Besides , It's cool to use a function and turn it into a single line of code .

Reduce

Reduce It's a function that turns iteration into something . Usually , You can use it on the list reduce Function performs a calculation to reduce it to a number . Reduce It looks like this :

We often use lambda Expression as function .

The product of a list is the multiplication of each individual number . To do this, you will write the following code :

But use reduce You could write it like this :

Get the same function , Code shorter , And it's cleaner with functional programming .( notes :reduce Function in Python3 Is no longer a built-in function , Need from functools Import in module )

Filter

filter Functions are iterated , And filter out everything you don't need in the iteration .

Usually ,filter You need a function and a list . It applies the function to each item in the list , If the function returns True, Do nothing . If you return False, Delete the item from the list .

The grammar is as follows :

Let's take a small example , No, filter We will write :

Use filter, It can be written like this :

Python As a developing and popular language , It's still being updated . In learning , It is suggested to find some learning partners to study and discuss together , The effect is better. . If you want to learn Python, Welcome to join Python Learning exchange group (627012464), We're going to urge , Learning together . There are development tools in it , A lot of dry goods and technical information sharing !

Higher order function

Higher order function can take function as parameter and return 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 .

Python All functions in 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

Pass as an argument to a function

Return... As the result of the function

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

Partial application

Partial application( Also known as closures ) It's a little strange. , But it's cool . You can call functions without providing all the parameters you need . Let's see that in an example . We want to create a function , It accepts 2 Parameters , A base and an index , And returns the cardinality of the exponential power , As shown below :

Now we want a special square function , Use the power function to square the number :

It works , But what if we want a cube function ? Or the function of finding the fourth power ? Can we continue to write them down ? ok , 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 , This will stop you from repeating . We can use closures here . Let's look at one that uses closures square Example of a function :

Isn't it cool ! We can only use 1 To call with two arguments, you need 2 A function of parameters .

We can also use a loop to generate a power function , This function runs from cube to 1000 The power of .

Functional programming is not pythonic

You may have noticed , A lot of what we want to do in functional programming revolves around lists . except reduce Functions and closures , All the functions you see generate lists . Guido(Python The father of ) Don't like Python The function in , because Python You already have a way to generate your own list .

If you are in the Python Write in an interactive environment ”import this“, You will get :

This is a Python zen . This is a song about Pythonic Poetry of what it means . The part we want to cover is :

There should be one — and preferably only one — obvious way to do it.( We should try to find one , It's better to be the only obvious solution )

stay Python in ,map and filter You can perform and list derivation ( Let's talk about ) The same operation . This breaks Python It's a rule of Zen , So these parts of functional programming are not considered “pythonic”.

Another topic is Lambda. stay Python in ,lambda Function is a normal function . Lambda It's grammar sugar . The two statements are equivalent .

Ordinary functions can perform lambda All the operations that a function can perform , But it can't work in the opposite way . lambda Functions can't do all the things that ordinary functions can do .

This is a short argument , Why functional programming doesn't fit the whole Python The ecological system . You may have noticed that I mentioned list derivation earlier , We're going to talk about them now .

The list of deduction

front , I mentioned that you can use map or filter Anything you do , You can use lists to deduce . List derivation is a kind of reasoning in Python How to generate a list in . Grammar is :

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

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

We can turn it into a list derivation , like this :

The list of supported if Such a statement . 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 , So using list derivation looks clearer , More easily . If we want to put each of the 0 What about the square of the following numbers ? With lambda,map and filter You can write :

It seems long and complicated . Infer by listing , It's just :

List derivation applies only to lists .map,filter Suitable for any iteratable object , So what's the use of that ? You can use any derivation for any iteratable object you encounter .

Other derivations

You can create a derivation for any iteratable object .

You can use derivation to generate any iteratable object . from Python 2.7 Start , You can even generate dictionaries (hashmap).

If it's iterative , Then you can generate it . Let's take a look at the last set of examples .

set It's a list of elements , There are no elements in the list that repeat twice .

set There is no order in the elements in .

You might notice set( aggregate ) And dict( Dictionaries ) With the same curly brackets . Python Very smart . Depending on whether you are dict Provide value , It will know that you are writing dict Derivation or set deduction .

summary

Functional programming is beautiful and pure . Functional code can be clean , But it can also be messy . some Python Programmers don't like Python Functional programming in . But I think , You should be able to solve the problem , Use the best tools .

In this paper, from https://juejin.cn/post/7043656047721971720, If there is any infringement , Please contact to delete .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved