When would you use reduce() instead of sum()?

后端 未结 4 1898
温柔的废话
温柔的废话 2021-01-02 00:52

I began learning functional programming recently, and came up with this example when attempting to calculate my quiz average for a class.

The example I came up with

相关标签:
4条回答
  • 2021-01-02 01:06

    reduce and sum do very different things. Consider a question like "I have a nested dictionary ...

    d = {'foo': {'bar': {'baz': 'qux'}}}
    

    and I would like to get the value associated with a list of keys: ['foo', 'bar', 'baz']". This could call for a reduce (if you're a functional programming kind of person):

    >>> reduce(lambda subdict, k: subdict[k], ['foo', 'bar', 'baz'], d)
    'qux'
    

    Note, you can't do this with sum. It just happens that summing is an easy example to show what is happening with reduce (since you can write it out with parenthesis and most programmers are familiar with how parenthesis group mathematical operations).

    0 讨论(0)
  • 2021-01-02 01:06

    Setting the performance issues aside, I have to say this: there's nothing wrong at all with using sum(), and stylistically you should choose sum() over reduce()! reduce() is more generic and thus can be used to write other reductions than just summing. sum() is a reduction that is common enough that it merits having its own name and definition.

    If you look at functional programming languages, you find for example that they have large libraries of generic utility functions for working with sequences, like Haskell's Data.List or Scheme's SRFI-1. A lot of the functions in those libraries could be written in terms of other ones; for example, the map function in Haskell could be written in terms of foldr (which is similar to reduce()):

    map :: (a -> b) -> [a] -> [b]
    map f = foldr go []
      where f a bs = f a : bs
    

    But nobody argues that foldr thereby makes map unnecessary or something to avoid. Rather, the more general operations like foldr or reduce() are seen as building blocks to construct more specialized functions that make programs easier to write and understand.

    reduce() and sum() are in the same relationship. reduce() is a building block that you reach to when you don't have a function like sum() already.

    0 讨论(0)
  • 2021-01-02 01:11

    reduce() makes sense when you require an arbitrary operation over a list of data, not when you already have a heavily optimized library function that will not only outperform reduce() on small lists, but drastically outperform it on larger ones.

    reduce() gives you the flexibility to create arbitrary folds, but that flexibility comes at the cost of some performance overhead, especially in a language where most basic functional constructs are considered slightly outside the mainstream.

    Python is "functional" in that it has first-class functions, but it is not primarily a functional language. It provides a lush supply of iterators for use in loops and has all sorts of language features that make explicit loops easy to write, but is not focused around recursively defined list operations (though it does permit them to a limited degree -- lack of TCO prevents me from, say, paraphrasing my Erlang or Guile code directly in Python, but does give me the flexibility to do things like benchmark competing approaches that adhere to similar interfaces).

    0 讨论(0)
  • 2021-01-02 01:17

    In place of sum? Never.

    But a reduce call would be the way to go when aggregating by a custom method.

    For instance product could be defined as:

    product = lambda iterable: reduce(operator.mul, iterable)
    

    Also sum is implemented in C.

    0 讨论(0)
提交回复
热议问题