[python] A first look at 'Functional Programming'

高洛峰
Release: 2017-02-16 11:09:49
Original
1268 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!