There has to be a simple way to do this, and I am obviously missing it :|
How do you add the items in a list\sequence (not clear on the difference) in clojure?
I've tried the following:
Clojure> (add [1 2 3])
java.lang.RuntimeException: Unable to resolve symbol: add in this context
Clojure> (+ [1 2 3])
java.lang.ClassCastException: Cannot cast clojure.lang.PersistentVector to java.lang.Number
Clojure> (apply merge-with + [1 2 3])
java.lang.IllegalArgumentException: Don't know how to create ISeq from: java.lang.Long
Clojure> (add-items [1 2 3])
java.lang.RuntimeException: Unable to resolve symbol: add-items in this context
(+ 1 2 3)
...will do it. @Nathan Hughes's solution:
(apply + [1 2 3])
...works if you have a reference to the sequence rather than defining it inline, e.g.:
(def s [1 2 3])
; (+ s) CastClassException
(apply + s) ; 6
As @4e6 notes, reduce
also works:
(reduce + s) ; 6
Which is better? Opinions vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With