I'm very new to Clojure and asking myself, how the arity of an anonymous function is defined/deducted.
Please consider the following poor-man count
function:
(reduce #(+ 1 %1) 0 '(1 2 3 55))
Running it with clojure I'm getting the following error message:
ArityException Wrong number of args (2) passed to: user/eval1157/fn--1158 clojure.lang.AFn.throwArity (AFn.java:429)
However, it works fine with JavaScript-Clojure and returns 4
as desired (you can execute the command here).
Changing the command by exchanging %1
->%2
to
(reduce #(+ 1 %2) 0 '(1 2 3 55))
would compile on both versions (but no longer work as count
). In this case seemingly, it can be deduced from %2
that there are at least two arguments.
So which version of Clojure is right? Am I allowed to feed an arbitrary amount of arguments to an anonymous function defined via #(...)
or only as many as mentioned inside of this function?
Should it be considered a bug in JavaScript-Clojure?
Edit: As have been explained in comments and in answer, that this is just the way how JavaScript works. There are differences to Java-Clojure, which are documented here, in particular:
There is currently no runtime enforcement of arity when calling a fn