Question: reduce Remember how, in class, we talked about map, which applies a function to every element of an array? Well, now we're going to write

reduce
Remember how, in class, we talked about map, which applies a function to every element of an array? Well, now we're going to write the companion function to map, which is called reduce. Just because such a notion is generally used in functional programming doesn't mean we can't build it in C!
What does reduce do? It combines all of the elements in an array with a specified function, cumulatively. It maintains a current cumulative value and applies the function to the cumulative value and each element of the given array in turn, in order to produce a new accumulator value. You might have noticed that several functions from hw2 had a similar shape -- they had to look at each element of a numerical array in turn and update a running value. Can we abstract that behavior out somehow? We can! That's what reduce does.
Concretely, this is exactly analogous to functools.reduce in Python 3. And for your edification as a computer scientist, this is operation is often called "fold".
reduce will look like int reduce(int *nums, int len, int (*f)(int,int), int initial).
initial is the initial value of the cumulative value, and f is a pointer to a function that takes two ints and returns an int -- the new value for the cumulative function. When we're calling the function f, imagine that its first parameter will be the current cumulative value, and the second parameter will be the next item in the input array, and the function f will return the new value for the cumulative value.
Why are we doing this? Well...

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!