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

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

    The actual answer to this (reduce) problem is: Just use a loop!

    initial_value = 0
    for x in the_list:
        initial_value += x #or any function.
    

    This will be faster than a reduce and things like PyPy can optimize loops like that.

    BTW, the sum case should be solved with the sum function

提交回复
热议问题