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

后端 未结 9 2017
被撕碎了的回忆
被撕碎了的回忆 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:22

    I may be quite late to the party, but we can create custom foldr using simple lambda calculus and curried function. Here is my implementation of foldr in python.

    def foldr(func):
        def accumulator(acc):
            def listFunc(l):
                if l:
                    x = l[0]
                    xs = l[1:]
                    return func(x)(foldr(func)(acc)(xs))
                else:
                    return acc
            return listFunc
        return accumulator  
    
    
    def curried_add(x):
        def inner(y):
            return x + y
        return inner
    
    def curried_mult(x):
        def inner(y):
            return x * y
        return inner
    
    print foldr(curried_add)(0)(range(1, 6))
    print foldr(curried_mult)(1)(range(1, 6))
    

    Even though the implementation is recursive (might be slow), it will print the values 15 and 120 respectively

提交回复
热议问题