Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (reduce * []) evaluate to 1?

Tags:

clojure

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 ?

like image 883
Denis Avatar asked May 29 '14 15:05

Denis


1 Answers

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)))
like image 164
juan.facorro Avatar answered Nov 17 '22 10:11

juan.facorro