Let's TDD clojure.core/reduce

From OO to Clojure Workshop!
Watch my free workshop to help you learn Clojure faster and shift your paradigm to functional.
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
TDD
my-reduce
(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
0 + 1
(my-reduce + 0 [1])
1
0 + 1 + 2
(my-reduce + 0 [1 2])
{.test-expression} 3
{.expected}
0 + 1 + 2 + 3
(my-reduce + 0 [1 2 3])
{.test-expression} 6
{.expected}
(sum (range 100))
(my-reduce + 0 (range 100))
{.test-expression} 4950
{.expected}
1 * 1
(my-reduce * 1 [1])
{.test-expression} 1
{.expected}
1 * 1 * 2
(my-reduce * 1 [1 2])
{.test-expression} 2
{.expected}
1 * 1 * 2 * 3
(my-reduce * 1 [1 2 3])
{.test-expression} 6
{.expected}
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!