i am going to play devil's advocate and argue for apply
.
reduce
is clojure's take on fold
(more exactly foldl
), the left-fold, and is usually defined with an initial element, because a fold operation has two parts:
so to find the sum of a set of numbers the natural way to use +
is as (fold + 0 values)
or, in clojure, (reduce + 0 values)
.
this explicitly shows the result for an empty list, which is important because it is not obvious to me that +
returns 0
in this case - after all, +
is a binary operator (all that fold
needs or assumes).
now, in practice, it turns out that clojure's +
is defined as more than a binary operator. it will take many or, even, zero values. cool. but if we're using this "extra" information it's friendly to signal that to the reader. (apply + values)
does this - it says "i am using + in a strange way, as more than a binary operator". and that helps people (me, at least) understand the code.
[it's interesting to ask why apply
feels clearer. and i think it's partly that you are saying to the reader: "look, +
was designed to accept multiple values (that's what apply is used for), and so the language implementation will include the case of zero values." that implicit argument is not present with reduce
applied to a single list.]
alternatively, (reduce + 0 values)
is also fine. but (reduce + values)
triggers an instinctive reaction in me: "huh, does +
provide a zero?".
and if you disagree, then please, before you downvote or post a reply, are you sure about what (reduce * values)
will return for an empty list?