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

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

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

前言

函数式编程的概念

简述

python中的函数编程

lambda

例如:

   1 lambda x: x+1

就生成了一个函数 λ(x) = x+1.

具有可以在python的解释器中试试:

   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

lambda的具体语法是:

lambda [parameter_list]: expression

parameter_list 是参数表, expression 是后面跟的表达式, lambda本身是个运算符, 作用在这两个元素上产生一个匿名函数, 类似于以下函数定义:

   1 def name(parameter_list):
   2     return expression

expression 是一个合法的python表达式, 显然 expression 中的变量量除了在 parameter_list 中的外必须是已知的.

注意experssion中是不能用print语句的, 要想产生输出的话可以用sys.stdout.write()等函数.

下面会不断给出 lambda 的例子

辅助算符

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]

如果map 的第一个参数, 即function等于None, 则默认为恒等变换. 例:

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

reduce

reduce( function, sequence[, initializer])

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

filter

filter( function, list)

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.

基本方法综述

应用实例

函数编程的缺陷

待补齐

例子

交流