必须有一个简单的方法来做到这一点,我显然错过了它:|
如何在clojure中的列表\序列中添加项目(区别不明确)?
我尝试了以下内容:
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
答案 0 :(得分:9)
(+ 1 2 3)
......会做的。 @Nathan Hughes的解决方案:
(apply + [1 2 3])
...如果您对序列有引用而不是内联定义,则有效,例如:
(def s [1 2 3])
; (+ s) CastClassException
(apply + s) ; 6
正如@ 4e6所述,reduce
也有效:
(reduce + s) ; 6
哪个更好? Opinions vary