7

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
mikera
  • 105,238
  • 25
  • 256
  • 415
javamonkey79
  • 17,443
  • 36
  • 114
  • 172

1 Answers1

9
(+ 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.

Community
  • 1
  • 1
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • 1
    I believe `(reduce + [1 2 3])` is more idiomatic. – 4e6 Dec 02 '11 at 20:16
  • @4e6: [You may be right.](http://stackoverflow.com/questions/3153396/clojure-reduce-vs-apply) – Craig Stuntz Dec 02 '11 at 20:21
  • 2
    (reduce + [1 2 3]) doesn't really make sense to me, since + already uses reduce: https://github.com/richhickey/clojure/blob/a1eff35124b923ef8539a35e7a292813ba54a0e0/src/clj/clojure/core.clj#L797 – Michiel Borkent Dec 03 '11 at 12:42
  • @4e6 as far as I can tell, a lot of clojurians seem to prefer (apply + [1 2 3]), although other lisps prefer reduce. I guess "apply" conveys the intent of the function better. – Adrian Mouat Dec 04 '11 at 12:36
  • (reduce + [1 2 3]) is probably best once the new Reducers functionality is released - reduce will get a lot more optimisations: http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-collection-processing.html – mikera Jul 19 '12 at 09:20