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

后端 未结 4 1899
温柔的废话
温柔的废话 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

    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.

提交回复
热议问题