multi-arity defn in Clojure -- first match first serve?

237 Views Asked by At

To be concrete, what is supposed to happen in the following situation:

(defn avg
  ([] 0)
  ([& args] (/ (reduce + args) (count args))))

(avg)

i.e., can I rely on clojure to always return 0 rather than divide-by-zero?

1

There are 1 best solutions below

3
On BEST ANSWER

You can rely on Clojure to return 0 rather than divide-by-zero. But it isn't first match, first served:

(defn avg
  ([& args] (/ (reduce + args) (count args)))
  ([] 0))

(avg)
; 0

The specific arities take precedence over the rest argument, as described here.