In clojure, calling reduce * on en empty collection returns 1. This is quite surprising.
I made this discovery while creating a factorial function, defined as follow :
(defn factorial [n] (reduce * (take-while #(> % 0) (iterate dec n))))
(factorial 0) is correctly returning 1, without me having to write a special case for zero.
How come ?
Checking the code for * and + shows that these two functions implement the 0-arity case by returning the identity for the operation. In the case of * the code is (with dosctring and metadata removed):
(defn *
([] 1)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (multiply x y)))
([x y & more]
(reduce1 * (* x y) more)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With