什么是函数式编程中的“折叠”函数的“pythonic”? [英] What is the 'pythonic' equivalent to the 'fold' function from functional programming?

查看:191
本文介绍了什么是函数式编程中的“折叠”函数的“pythonic”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  foldl(+)0 [1]在Haskell中实现类似以下内容的最习惯方法是什么? ,2,3,4,5] 
- > 15

或者等同于Ruby:

  [1,2,3,4,5] .inject(0){| m,x | m + x} 
#> 15

显然,Python提供了 reduce 函数,这是一个fold的实现,完全如上,然而,我被告知,'pythonic'编程方式是为了避免 lambda 项和高阶函数,宁愿在可能的情况下列表理解。因此,在Python中是否存在一种不是 reduce 函数的列表或类似列表的结构的折叠方式,或者是 reduce 实现此目的的习惯方式?

解决方案

总结一个数组的Pythonic方式是总和。出于其他目的,您可以使用 reduce 运算符模块的组合,例如

  def product(xs):
return reduce(operator.mul,xs,1)

请注意, reduce 其实是 foldl foldr ,而实际上使用 reduce 的非关联运算符是被认为是不好的风格。



使用高阶函数是pythonic;它充分利用了Python的原则,即一切都是一个对象,包括函数和类。你是对的,lambdas被一些Pythonistas皱起了眉头,但主要是因为它们在复杂时往往不易读。


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 Ruby:

[1,2,3,4,5].inject(0) {|m,x| m + x}
#> 15

Obviously, Python provides the reduce function, which is an implementation of fold, exactly as above, however, I was told that the 'pythonic' way of programming was to avoid lambda terms and higher-order functions, preferring list-comprehensions where possible. Therefore, is there a preferred way of folding a list, or list-like structure in Python that isn't the reduce function, or is reduce the idiomatic way of achieving this?

解决方案

The Pythonic way of summing an array is sum. For other purposes, you can sometimes use some combination of reduce and the operator module, e.g.

def product(xs):
    return reduce(operator.mul, xs, 1)

Be aware that reduce is actually a foldl, in Haskell terms. There is no special syntax to perform folds, there's no builtin foldr, and actually using reduce with non-associative operators is considered bad style.

Using higher-order functions is quite pythonic; it makes good use of Python's principle that everything is an object, including functions and classes. You are right that lambdas are frowned upon by some Pythonistas, but mostly because they tend not to be very readable when they get complex.

这篇关于什么是函数式编程中的“折叠”函数的“pythonic”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆