High-order function learning of Python functional programming

Source: Internet
Author: User

Basic concepts

Functional programming is a highly abstract programming paradigm, and functions written in purely functional programming languages have no variables. Therefore, any function, as long as the input is determined, the output is determined by this function we call the pure function, we call this function without side effects. In the case of programming languages that allow the use of white variables, the same input may have different outputs because the variable state inside the function is indeterminate, and we call this function to have side effects.
One feature of functional programming is that it allows the function itself to be passed as an argument to another function, and also allows a function to be returned!
Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.
(This part of the content excerpt with Liaoche Teacher's blog article, oneself also carried on the study)

Higher order functions
    • Variables can point to functions

      #变量可以指向函数f = abs;print(abs(-10));#10print(f(-10));#10#在这里用f和abs调用的结果和效果是一样的

      The description variable F already points to the function abs itself.

    • The function name is also a variable
      A function name is a variable that points to a function. Such as:

      abs = 10;print(abs(-10));# Traceback (most recent call last):#   File "test01.py", line 164, in <module>#     print(abs(-10));# TypeError: ‘int‘ object is not callable

      ABS has been assigned a value of 10, is a variable pointing to 10, it can not be called by ABS (-10) to call the function, because the ABS variable has not pointed to the absolute value of the function.

    • Incoming function
      A function can be a parameter to another function, which is called a higher order function.

      #一个简单的高阶函数def add(x, y, f):    return f(x) + f(y);print(add(5, -6, abs));#11
Map/reduce

Python has the map () and reduce () functions built into it.

    • Map () function
      The map function receives two parameters, one is a function, the other is a iterable (an iterative object), and map functions the incoming function to each element of the sequence at once and returns the result as a new iterator.

      #map()函数def f(x):    return x * x;r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]);print(list(r));# [1, 4, 9, 16, 25, 36, 49, 64, 81]
    • Reduce () function
      The function must receive two parameters, reduce the function results continue and the next element of the sequence to do the cumulative calculation.
      such as: Cumulative

      #reduce()函数from functools import reduce;def add1(x, y):    return x + y;print(reduce(add1, [1, 3, 5, 7, 9]));#25

      This is not where reduce comes in, and when we turn the sequence above into an integer 13579, reduce is useful:

      def fn(x, y):    return x * 10 + y;print(reduce(fn, [1, 3, 5, 7, 9]));

      This example doesn't make sense, but when we're going to convert the string str into an int function, we use reduce (combined with map).

Filter () function
    • Filter
      Python's built-in filter function is used for filtering sequences. Similar to map also receives a function and a sequence, but the difference is that the filter functions the passed-in function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.
      In a list, delete the even number, leaving only the odd number:

      #filter函数#在一个list中删除偶数,只保留奇数def is_odd(n):    return n % 2 == 1;print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])));# 1, 5, 9, 15
    • Using filter to calculate prime number
      Thought: One way to calculate prime numbers is the method of the Fourier sieve, and its algorithms are very simple to understand:

    1. First, list all the natural numbers starting with 2, and construct a sequence:

      2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
    2. Take the first number of the sequence 2, it must be a prime, and then sift out the multiples of 2 of the sequence with 2:

      3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
    3. Take the first number of a new sequence of 3, it must be a prime, and then sift out the multiples of 3 of the sequence 3:

      5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
    4. Take the first number of the new sequence 5, and then sift out the multiples of 5 of the sequence with 5:

      7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

Keep sifting down and you can get all the primes.
Note: This algorithm describes the article from the Liaoche teacher.

Sorted () function

Sorting algorithms

#sorted函数排序print(sorted([36, -2, 5, 7, 1, -10]));# [-10, -2, 1, 5, 7, 36];

Sorted is also a high-order function that accepts a key function to implement a custom sort, sorted by the absolute size of the column:

#sorted函数排序print(sorted([36, -2, 5, 7, 1, -10], key=abs));# [1, -2, 5, 7, -10, 36]

The sorted function can be used to sort strings.
Sorted () is also a higher-order function. The key to sorting with sorted () is to implement a mapping function.

Summarize

Learning this part of functional programming is more important, learning this part reminds me of the front-end framework Reactjs,react is also the emphasis on functional programming, but also react characteristics. This means that a function can be used as an argument to another function. The learning examples above are simple and need to be practiced constantly.

High-order function learning of Python functional programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.