Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add items in a list/sequence in Clojure

Tags:

clojure

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
like image 784
javamonkey79 Avatar asked Dec 02 '11 19:12

javamonkey79


1 Answers

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

like image 115
Craig Stuntz Avatar answered Oct 13 '22 05:10

Craig Stuntz