search
HomeBackend DevelopmentPython Tutorial[python] A first look at 'Functional Programming'

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).

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>
>>> min
<built-in></built-in></built-in>

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</module></stdin>

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

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)]

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

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

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]

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]

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

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)

After this definition, we call the f function:

>>> f()
WARNING:root:f is running
in function f

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")

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

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'

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'

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

@a
@b
@c
def f ():


# 等价于

f = a(b(c(f)))

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
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
Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.