函数fold 或reduce用法

http://yi-programmer.com/2011-02-24_fold.html

http://c2.com/cgi/wiki?FoldFunction

http://rwh.readthedocs.org/en/latest/chp/4.html

The PythonLanguage calls it reduce; this is a left fold:

  reduce(operator.add, [1,2,3,4])
  reduce(lambda x,y: x+y, [1,2,3,4])

You can get the effect of the parameter called initial above by giving an optional third argument.

In Python 3.x it has been moved to "functools.reduce".

python foldl和foldr实现:

def foldl(f,z,xs):
    if not xs:
        return z
    else:
        return foldl(f,f(z,xs[0]),xs[1:])

def foldr(f,z,xs):
    if not xs:
        return z
    else:
        return f(xs[0],foldr(f,z,xs[1:]))

a=[1,2,3,4,5]
import operator
print foldl(operator.add,1,a)
print foldr(operator.add,1,a)

foldl:

 (((((init+1)+2)+3)+4)+5)

folr:

(1+(2+(3+(4+(5+init))))))

在函数式语言中,列表这个结构是通过空列表 nil 和操作符 cons 进行定义的,haskell中对应有 [] 和 (:) 的语法糖。所以[1,2,3,4,5] 实际上是 1:[2:[3:[4:[5:[]]]]] ,这样一来,我们可以从一个新的视角看待 fold 操作, foldr (+) [] 操作其实就是将操作符 (:) 替换为 (+) :

参考了:http://stackoverflow.com/questions/9204209/tutorial-for-summation-recursion-in-python

原文地址:https://www.cnblogs.com/youxin/p/3427435.html