I am very new to Clojure and I have a simple issue to resolve, which Googling didn't help with. Just as an exercise in learning how to create functions in Clojure, I tried to make a function which takes the values of a vector and calculates their arithmetic mean, in the following manner:
(defn mean [vec]
( let [x (reduce + vec), y (count vec)]
(x / y)
))
When I run this in my interpreter after creating a vector of name vec_foo by typing (mean vec_foo)
, I get the following message:
Execution error (ClassCastException) at user/mean (REPL:1). class java.lang.Long cannot be cast to class clojure.lang.IFn (java.lang.Long is in module java.base of loader 'bootstrap'; clojure.lang.IFn is in unnamed module of loader 'app')
When trying (apply mean vec_foo)
, the following message appears instead:
Execution error (ArityException) at user/eval369 (REPL:1). Wrong number of args (5) passed to: user/mean
My initial goal was to just get the average of the vectors values as an output, but these error messages are also very interesting. Any information on either the error messages' meaning, or solving the problem, will be appreciated.
In your code, x
is always a Long
When you run (x / y)
, it tries to invoke x
as a function, but you can't cast a Long to a function.
What you are trying to do is (/ x y)
About sum
, as you didn't share the implementation, I can only guess: probably (sum vec_foo)
works.