How to use shorthand and proper use

I am learning Clojure, and actually I am doing some exercises, but I am stuck in a problem:

I need to make a function sum-consecutivesthat sums up consecutive elements in an array, resulting in a new example:

[1,4,4,4,0,4,3,3,1]  ; should return [1,12,0,4,6,1]

I made this function that should work fine:

(defn sum-consecutives [a]
  (reduce #(into %1 (apply + %2)) [] (partition-by identity a)))

But this causes an error:

IllegalArgumentException I do not know how to create an ISeq from: java.lang.Long clojure.lang.RT.seqFrom (RT.javaβ–Ί42)

Can someone help me figure out what's wrong with my func? I have already searched for this error on the Internet, but have not found any useful solutions.

+4
source share
2 answers

, conj into, into , a 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)))
+2

, partition-by. , , .

(let [xs [1 4 4 4 0 4 3 3 1]]
  (partition-by identity xs))  ;=> ((1) (4 4 4) (0) (4) (3 3) (1))

, reduce ( apply ); :.

(reduce + [4 4 4])  ;=> 12

reduce map:

(let [xs [1 4 4 4 0 4 3 3 1]]
  (map #(reduce + %) (partition-by identity xs)))  ;=> (1 12 0 4 6 1)

...

xs ( Clojure ).

let .

, -.

, , , :

(defn sum-consecutives [coll]
  (map #(reduce + %) (partition-by identity coll)))
+2

Source: https://habr.com/ru/post/1681653/


All Articles