函数编程, 任何人可以以任何方式随意转载.

清剿太监贴~~ , 把没完成的东西完成之

-- hoxide [DateTime(2004-09-08T23:06:48Z)] TableOfContents

前言

函数式编程的概念

python中的函数编程

lambda

   1 lambda x: x+1

   1 >>> lambda x: x+1 # 生成一个匿名函数 λ(x) = x+1
   2 <function <lambda> at 0x00C99770>
   3 >>> f = lambda x: x+1 # 将这个函数绑定名字 'f'
   4 >>> f(1) # 调用 'f'
   5 2

   1 def name(parameter_list):
   2     return expression

高阶函数

map

   1 >>> a = range(5);
   2 >>> b = range(4);
   3 >>> map(lambda x, y: (x, y) , a, b) # lambda x,y 接受两个参数, 生成个包含这两个参数的tuple.
   4 [(0, 0), (1, 1), (2, 2), (3, 3), (4, None)]

   1 >>> ml = [[0, 1], [2, 3], [3, 4]]
   2 >>> map(lambda (x,y): x+y , ml) # lambda (x,y): x+y 接受一个有两元元组(tuple), 计算他们的和.
   3 [1, 5, 7]

   1 >>> a = range(3)
   2 >>> map(None , a)
   3 [0, 1, 2]

reduce

reduce( function, sequence[, initializer])

将函数function从左到右作用在序列的每个元素上, 函数function为二元函数, 第一个变量为上次计算所得结果,第二个变量为列表元素. 具体得:

   1 >>> reduce(lambda x,y: x+y , [1,2,3,4,5]) # 相当于 ((((1+2)+3)+4)+5)
   2 15

整个计算过程就像列表在不断缩减一样.

initializer为初值. 例如:

>>> reduce(lambda x,y: x+y , [1,2,3,4,5], 10) # 相当于(((((10+1)+2)+3)+4)+5)
25

filter

filter( function, list)

filter 过滤器.

构造一个列表 Construct a list from those elements of list for which function returns true. list may be either a sequence, a container which supports iteration, or an iterator, If list is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of list that are false (zero or empty) are removed. Note that filter(function, list) is equivalent to [item for item in list if function(item)] if function is not None and [item for item in list if item] if function is None.

基本方法综述

应用实例

函数编程的缺陷

待补齐

例子

交流