Table of Contents
Functional Programming
Higher-order functions
map/reduce
filter
sorted
Decorator
Simple decorator
Decorator with parameters
Further understanding
Summary
Home Backend Development Python Tutorial [python] A first look at 'Functional Programming'

[python] A first look at 'Functional Programming'

Feb 16, 2017 am 11:09 AM
python

Functional Programming

Last semester I took a class called 'Artificial Intelligence'. The teacher forced us to learn a language called prolog. Wow, it felt really uncomfortable. The way of thinking was completely different from what we learned before. My life was different. I thought about writing the Tower of Hanoi for a long time. Finally, I found a piece of code on the Internet and modified it (for fear of being found by the teacher to have plagiarized it) before writing it. I posted a paragraph to get a feel for it:

hanoi(N) :- dohanoi(N, 'a', 'b', 'c').
dohanoi(0, _ , _ , _ )    :- !.
dohanoi(N, A, B, C)    :-
  N1 is N-1,
  dohanoi(N1, A, C, B),
  writeln([move, N, A-->C]), 
  dohanoi(N1, B, A, C).
Copy after login

At that time, it was I almost understand it, but the main reason is that there is too little information and debugging is out of the question. Whenever I encounter a bug, I just get stuck. I feel a little dizzy now. However, it is said that prolog could compete with Lisp back then, and I have become a little interested in Lisp recently. After finishing these things, I will pay homage to this type of functional language.

What is functional programming? Liao Da wrote here:

Functional programming is a programming paradigm with a high degree of abstraction. Functions written in a purely functional programming language have no variables. Therefore, for any function, as long as the input is Determined, the output is determined. We call this pure function without side effects. In programming languages ​​that allow the use of variables, since the variable status inside the function is uncertain, the same input may result in different outputs. Therefore, this kind of function has side effects.

Maybe you still don’t understand it after reading it. Don’t worry, let’s read these sections first.

Higher-order functions

In mathematics and computer science, a higher-order function is a function that satisfies at least one of the following conditions:

  • Accepts one or more A function as input

  • Output a function

That is, pass the function itself as a parameter, or return a function.

For example, you can assign a function to a variable like a normal assignment:

>>> min(1, 2)
1
>>> f = min
>>> f(1, 2)
1
>>> f
<built-in function min>
>>> min
<built-in function min>
Copy after login

You can also assign a value to a function (code continues):

>>> min = 10
>>> min(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> f(1, 2)
1
>>> min = f
>>> min(1, 2)
1
Copy after login

You can also pass parameters, for example , a function that calculates the sum of all numbers:

>>> def add(a, b):
...     return a+b
...

>>> def mysum(f, *l):
...     a = 0
...     for i in l:
...             a = f(a, i)
...     return a
...
>>> mysum(add, 1, 2, 3)
6
>>> mysum(add, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
55
Copy after login

Of course, replacing this f with multiplication means calculating the product of all numbers.

Let’s take a look at some of the higher-order functions built into Python, which are often used.

map/reduce

I remember vaguely hearing this word when I took a cloud computing course last semester, but the class was very boring, so I didn’t listen to it much. I didn’t seem to notice it when I saw it here. Too same? ?

But there’s not much to say, let’s briefly talk about the role of each function.

For map, its calculation formula can be seen like this:

map(f, [x1, x2, ..., xn]) = [f(x1), f(x2), ..., f(xn)]
Copy after login

For reduce, its calculation formula can be seen like this:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
Copy after login

Liao Da made it very clear. .

filter

filter is similar to the map function, accepting a function and iterable, and returning a list, but its function is to determine whether to retain the value based on whether the function return value is True. For example:

def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
Copy after login

sorted

The sorted function is also a higher-order function. Passing the function to the parameter key can process the sequence to be sorted through the key function and then sort it, but the sequence will not be changed. The value, for example:

>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
Copy after login

Decorator

I won’t talk about the anonymous function. I’ll look at it carefully when I use it later. I remember studying the decorator for a long time when I looked at flask. , let’s review it again this time.

Simple decorator

The first is a simple decorator, which prints out the log before each function call:

import logging

def log(func):
    def wrapper(*args, **kw):
        logging.warn("%s is running" % func.__name__)
        func(*args, **kw)
    return wrapper
Copy after login

This is an extremely simple decorator, how about What about using it? The first usage I saw was to add @ before the function that needs to be decorated, but in fact this is a syntactic sugar of Python. The most original usage is more understandable. First define a function f:

def f():
    print("in function f")

f = log(f)
Copy after login

After this definition, we call the f function:

>>> f()
WARNING:root:f is running
in function f
Copy after login

The result of using @log is the same. In fact, the @ symbol serves as the syntax sugar of the decorator and has the same function as the previous assignment statement, making the code more visible. It is more concise and clear, avoiding another assignment operation, like the following:

@log
def f():
    print("in function f")
Copy after login

Decorator with parameters

Sometimes we also need to pass in parameters to the decorator, for example, status , level and other information, you only need to 'wrap' a layer of functions outside the wrapper function, as shown below:

import logging

def log(level):
    def decorator(func):
        def wrapper(*args, **kw):
            logging.warn("%s is running at level %d" % (func.__name__, level))
            return func(*args, **kw)
        return wrapper
    return decorator

@log(2)
def f():
    print("in function f")
    
>>> f()
WARNING:root:f is running at level 2
in function f
Copy after login

Further understanding

In order to further understand the decorator, we can print out the function The name attribute of f:

#对于不加装饰器的 f,其 name 不变
>>> def f():
...     print("in function f")
...
>>> f.__name__
'f'

#对于添加装饰器的函数,其 name 改变了
>>> @log
... def f():
...     print("in function f")
...
>>> f.__name__
'wrapper'
Copy after login

Contact the first decorator assignment statement, and you can roughly understand what happened: f = log(f) so that f points to log(f ), that is, the wrapper function. Each time the original function f is run, the wrapper function will be called. In our example, the log is printed first and then the original function f is run.

However, there is a problem with this. This causes the meta-information of the original function f to be replaced, and a lot of information about f disappears. This is difficult to accept, but fortunately we have the functools module. Modify The function is:

import functools
import logging

def log(func):
    functools.wraps(func)
    def wrapper(*args, **kw):
        logging.warn("%s is running" % func.__name__)
        func(*args, **kw)
    return wrapper

>>> @log
... def f():
...     print("in function f")
...
>>> f.__name__
'f'
Copy after login

In addition, you can add multiple decorators to the same function:

@a
@b
@c
def f ():


# 等价于

f = a(b(c(f)))
Copy after login

Summary

I don’t know much about functional programming, here is just Now that you have a rough understanding of the concept, it is definitely more common to use imperative programming. However, there are languages ​​that are purely functional, such as Haskell or Lisp, and learning them will open up a new way of thinking.

For more [python] articles related to "Functional Programming", please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles