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
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).