What is the 'pythonic' equivalent to the 'fold' function from functional programming?

后端 未结 9 2019
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 00:03

What is the most idiomatic way to achieve something like the following, in Haskell:

foldl (+) 0 [1,2,3,4,5]
--> 15

Or its equivalent in

9条回答
  •  时光取名叫无心
    2020-12-01 00:12

    You can reinvent the wheel as well:

    def fold(f, l, a):
        """
        f: the function to apply
        l: the list to fold
        a: the accumulator, who is also the 'zero' on the first call
        """ 
        return a if(len(l) == 0) else fold(f, l[1:], f(a, l[0]))
    
    print "Sum:", fold(lambda x, y : x+y, [1,2,3,4,5], 0)
    
    print "Any:", fold(lambda x, y : x or y, [False, True, False], False)
    
    print "All:", fold(lambda x, y : x and y, [False, True, False], True)
    
    # Prove that result can be of a different type of the list's elements
    print "Count(x==True):", 
    print fold(lambda x, y : x+1 if(y) else x, [False, True, True], 0)
    

提交回复
热议问题