Function-Type programming
函数是Python内建支持的一种封装,而函数式编程通俗说来就是把函数本身作为参数传入另一个函数,允许返回一个函数。
The function name is also a variable, and can be assigned a value. If the function name is assigned to a different value, it no longer points to the original.
高阶函数:既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
At this point, you can learn several higher-order functions :
-Map/reduce
可借鉴Google论文[MapReduce: Simplified Data Processing on Large Clusters](http://research.google.com/archive/mapreduce.html)
Map (func, Iterator)
第一个参数即为函数名,第二个参数即为一个列表,map将传入的函数依次作用到序列的每一个元素上,并返回一个新的列表Iterator。
def abc(x): return x * xr = map(abc, [1, 2, 3, 4, 5, 6, 7, 8, 9])list(r)结果:[1, 4, 9, 16, 25, 36, 49, 64, 81]
Note: Loops can also get the same result, but multiple lists are generated.
Reduce (func, Iterator)
reduce把结果和序列的下一个元素做累积计算。reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
General example: STR to int
from functools import reduceDIGITS = {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}def char2num(s): return DIGITS[s]def str2int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s))print(str2int("124432"))
结果:124432
-Filter (func, Iterator)
用于过滤序列(筛选)。fifter把传入的函数作用于每个元素之后,根据传入函数的返回值是True还是False决定保留还是丢弃该元素,最终还是返回列表。
Example: Using filter to calculate prime numbers
One way to calculate prime numbers is through the method of the Fourier sieve, which is very simple to understand:
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, ...
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, ...
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, ...
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.
Using Python to implement this algorithm, you can first construct an odd sequence starting with 3:
def _odd_iter(): n = 1 while True: n = n + 2 yield n
Note that this is a generator and is an infinite sequence.
Then define a filter function:
def _not_divisible(n): return lambda x: x % n > 0
Finally, define a generator that continually returns the next prime number:
def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列
The generator returns the first prime number 2, and then uses filter () to generate a new sequence of filters.
Since primes () is also an infinite sequence, it is called to set a condition for exiting the loop:
# 打印1000以内的素数:for n in primes(): if n < 1000: print(n) else: break
Notice that the iterator is a sequence of lazy computations, so we can use Python to represent the sequence of "all natural numbers", "All primes", and the code is very concise.
-Sorted ()
排序算法:排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来。 sorted(list, key=func, reserve=False):按key接收的函数作用在list的每个元素上之后的返回值进行排序, * 而返回的是对应原来的元素*,reserve为反向排序。
return function
函数作为函数的返回值。
def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sumf = lazy_sum(1, 3, 5, 7, 9)f()
结果:25
注意点:即使传入相同的参数,返回的也不是同一个函数。
Python mid---02 functional programming