1

This function

(defn sum [& args] (apply + args))

should sum up all args sequence elements throws an exception. Why?

user> (defn sum [& args] (apply + args))
#'user/sum
user> (sum [1 2 3])
ClassCastException   java.lang.Class.cast (Class.java:2999)
user> (sum (range 1 10))
ClassCastException   java.lang.Class.cast (Class.java:2999)

(also used as example (which does not compile for me) in this question How to make a Clojure function take a variable number of parameters?)

I'm using nrepl in Emacs 24.2 Live with Clojure 1.5.1

Community
  • 1
  • 1

2 Answers2

3

When you specify a function parameter with & args, that means that args will contain a list of all further function parameters. In this case, sum is getting a list of all of its parameters--but its parameter is already a list, so effectively what sum is doing here is

(apply + [[1 2 3]])

If you get rid of the & in your definition of sum's parameters (so that the list is just [args]) you'll get what you want.

bdesham
  • 15,430
  • 13
  • 79
  • 123
0

Try the following. In Clojure variable arguments are lists itself

(sum 1 2 3)
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105