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
2
  • 2
    you mean like (apply + [1 2 3]) ? Commented Dec 2, 2011 at 19:36
  • Yes, @NathanHughes - that is what I was looking for. I don't know why I couldn't figure something so simple out, but yes - that was it. Commented Dec 2, 2011 at 21:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I believe (reduce + [1 2 3]) is more idiomatic.
(reduce + [1 2 3]) doesn't really make sense to me, since + already uses reduce: github.com/richhickey/clojure/blob/…
@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.
(reduce + [1 2 3]) is probably best once the new Reducers functionality is released - reduce will get a lot more optimisations: clojure.com/blog/2012/05/08/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.