Let's TDD clojure.core/reduce

Summary: clojure.core/reduce is a powerful function, yet the code for it is so simple. It's four lines! We TDD our own implementation.

A couple of weeks ago I introduced a TDD-in-the-browser system and applied it to build map. reduce is another cornerstone of functional programming. I explained how reduce works recently, so that should help understand it from the outside.

But how does it work from the inside? Let's write a version of reduce.

Specification

Define a function my-reduce. It should take three arguments. The first argument, f, is a function. The second argument is the initial value. And the third argument is a collection of values. f is a function of two arguments. my-reduce should take one value from the collection and apply f to the initial argument and the first value. The return value of f will become the new initial value, and then

COMMING SOON

Conclusion

clojure.core/reduce is a very useful function. It's one of those functions I wish I had started using earlier. And building a version of reduce yourself can help you understand how the recursion works.

I hope you like it. If you liked this, you may like LispCast Introduction to Clojure. It's a video course about Clojure, starting from the ground up. It has exercises, animations, visuals, and code. Try it!