clojureoverloadingaritydefn

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


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?


Solution

  • 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.