14 thoughts on “map(), filter() and reduce() explained.

  1. How does reduce work here? Is it like a function that gets called on each element, but also with the result of the previous elements? How does it keep the context/state required to combine every element in an array into a single output?

    Like

  2. Andrew Brown You guessed it. A reduction is a function applied successively to each element with an additional argument, the accumulated value. This value is carried from its initial state (which you can provide) and must be passed back as the function result so it can be passed to the next calculation.

    This is most powerful operation because with it you can create the other two operations or you can use it to calculate a length, a sum or an average etc. You can also use it to compose higher level functions (functions built out of other functions).

    Like

  3. Yes it’s pretty standard. It’s also known as a fold operation. Usually these operations come in pairs so you can process from left to right or right to left.

    Like

  4. reduce usually gets an initial value as the reduce function combines two values, the current item of the list and the result of the previous reduce.

    In lack of an initial element the neutral element wrt the reduce function and the set of elements can be used (0 with integer addition, 1 with multiplication etc).

    What is the initial or neutral element in this case? Maybe air?

    Like

  5. Shit is a Maybe monad with a value of Exists or None. I think Shit is also a monoid with an identity of None. Shit can be appended to in a reduction operation but appending anything other than None to it produces Exists.

    Like

Leave a comment