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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles