2

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?

manualcrank
  • 93
  • 1
  • 5

1 Answers1

6

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.

Thumbnail
  • 13,293
  • 2
  • 29
  • 37
  • Thank-you. I believe you, but I'm not seeing, or else not understanding, the description as such. Are you referring to this: "One and only one overload can itself be variadic, by specifying the ampersand followed by a single rest-param. Such a variadic entry point, **when called with arguments that exceed the positional params**, will find them in a seq contained in the rest param. If the supplied args do not exceed the positional params, the rest param will be nil." – manualcrank Apr 15 '14 at 23:10
  • @manualcrank My interpretation is: only if there are more arguments than *any* explicit arity encompasses is *the* version with the rest argument matched (I need sleep before further exegesis :( ). – Thumbnail Apr 15 '14 at 23:20
  • Ok that makes sense here too, i.e. the variadic entry point is not taken in this example because no parameters does not exceed zero positional parameters. – manualcrank Apr 15 '14 at 23:24