Reputation: 10389
Can someone explain the behavior in the Clojure code below?
I don't get it.
Does Clojure somehow replace or "optimize" function arguments? Why does calling a function with a single nil argument result in an ArityException
?
(defn foo [bar] (reduce #(%1) bar))
(foo nil)
-> ArityException Wrong number of args (0) passed to: test$foo$fn clojure.lang.AFn.throwArity (AFn.java:437)
Upvotes: 1
Views: 695
Reputation: 84369
See (doc reduce)
:
[...] If coll contains no items, f must accept no arguments as well, and reduce returns the result of calling f with no arguments. [...]
Here coll is nil
, which is effectively being treated as a collection containing no items (as it usually is in similar contexts), and f
is #(%1)
.
Thus #(%1)
is being called with no arguments and ends up throwing the exception you see.
Upvotes: 5