我正在学习 Clojure,实际上我正在做一些练习来练习,但我遇到了一个问题:
我需要创建一个 sum-consecutives
函数,它将数组中的连续元素相加,从而产生一个新元素,例如:
[1,4,4,4,0,4,3,3,1] ; should return [1,12,0,4,6,1]
我做了这个函数,应该可以正常工作:
(defn sum-consecutives [a]
(reduce #(into %1 (apply + %2)) [] (partition-by identity a)))
但它抛出一个错误:
IllegalArgumentException Don't know how to create ISeq from: java.lang.Long clojure.lang.RT.seqFrom (RT.java:542)
谁能帮我看看我的函数出了什么问题吗?我已经在网上搜索过此错误,但没有找到有用的解决方案。
最佳答案
您可能想要使用conj
而不是 into
,因为 into
期望它的第二个参数是 seq
:
(defn sum-consecutives [a]
(reduce
#(conj %1 (apply + %2))
[]
(partition-by identity a)))
(sum-consecutives [1,4,4,4,0,4,3,3,1]) ;; [1 12 0 4 6 1]
或者,如果您确实想要使用 into
,您可以将对 apply +
的调用包装在矢量文字中,如下所示:
(defn sum-consecutives [a]
(reduce
#(into %1 [(apply + %2)])
[]
(partition-by identity a)))
关于clojure - 如何正确使用reduce和into,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45156101/