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
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
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
(and js/window js/window.cljs js/window.cljs.user (js-delete js/window.cljs.user "my_reduce"))
;; This is a live editor. Make changes to turn the tests above green. (defn my-reduce [f init coll])
empty list returns init
(my-reduce + 0 )
0 + 1
(my-reduce + 0 )
0 + 1 + 2
(my-reduce + 0 [1 2])
0 + 1 + 2 + 3
(my-reduce + 0 [1 2 3])
(sum (range 100))
(my-reduce + 0 (range 100))
1 * 1
(my-reduce * 1 )
1 * 1 * 2
(my-reduce * 1 [1 2])
1 * 1 * 2 * 3
(my-reduce * 1 [1 2 3])
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!