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

后端 未结 9 2043
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  旧时难觅i
    2020-12-01 00:15

    Haskell

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

    Python

    reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

    Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

    For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

    That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

提交回复
热议问题