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

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

-- 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])

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.

基本方法综述

应用实例

函数编程的缺陷

待补齐

例子

交流