Welcome! Please see the About page for a little more info on how this works.

+1 vote
in ClojureScript by

In cljs:

app:cljs.user=> (apply max [])
nil

In clj:

> (apply max [])
Execution error (ArityException) at redacted.ns/eval26821 (form- 
init217321140160545149.clj:741).
Wrong number of args (0) passed to: clojure.core/max

Not sure which behavior I prefer (maybe cljs?), but this results in surprising-to-me outcomes in our application.

2 Answers

0 votes
by

"Expect the unexpected", because calling max with no arguments does not adhere to its contract. It's practically undefined behavior.

by
Thank you for your answer, can you point me to the contract to which you're referring?
by
The very signature of the function.
by
You make a good point. I will try to formulate a better question about zero arity application of functions with these sorts of signatures. Thanks! (:
by
It's literally undefined behavior. `max` returns the greatest of 1 or more numbers. There is no answer if there are 0 numbers.
0 votes
by

You could argue that this is because max have doesn't have a reasonable, general identity value (nor does min), but you could supply one of your own choosing, eg Integer/MIN_VALUE:

user=> (apply max Integer/MIN_VALUE [])
-2147483648
user=> (apply max Integer/MIN_VALUE [2])
2
user=> 
by
I appreciate this thought, and being explicit about the bounds is a good idea. I think we got closer to the root of the confusion in this later question (https://ask.clojure.org/index.php/12051/apply-behaves-differently-in-clj-cljs-with-empty-argument), there are different expectations between the JVM and JavaScript about applying functions with the wrong number of arguments, and I am now convinced that the behavior on both hosts is justified (and the difference between them is both potentially confusing and ultimately ok).
by
As an afterthought, I guess if you use `reduce` rather than `apply`, you could follow the good advice from Rich Hickey as to not use the two arity version of `reduce`

  user=> (reduce max [])
  Execution error (ArityException) at user/eval9 (REPL:1).
  Wrong number of args (0) passed to: clojure.core/max
  user=> (reduce max Integer/MIN_VALUE [])
  -2147483648
  user=> (reduce max Integer/MIN_VALUE [2])
  2
  user=>
...