I would like to βchunkβ seq in subseqs the same way as for the section, except that the function is not applied to each individual element, but to a range of elements.
So for example:
(gather (fn [ab] (> (- ba) 2)) [1 4 5 8 9 10 15 20 21])
will result in:
[[1] [4 5] [8 9 10] [15] [20 21]]
Similarly:
(defn f [ab] (> (- ba) 2)) (gather f [1 2 3 4]) ;; => [[1 2 3] [4]] (gather f [1 2 3 4 5 6 7 8 9]) ;; => [[1 2 3] [4 5 6] [7 8 9]]
The idea is that I apply the beginning of the list and the next element to the function, and if the function returns true, we split the current list title to this point into a new section.
I wrote this:
(defn gather [pred? lst] (loop [acc [] cur [] l lst] (let [a (first cur) b (first l) nxt (conj cur b) rst (rest l)] (cond (empty? l) (conj acc cur) (empty? cur) (recur acc nxt rst) ((complement pred?) ab) (recur acc nxt rst) :else (recur (conj acc cur) [b] rst)))))
and it works, but I know there is an easier way. My question is:
Is there a built-in function for this where this function is not needed? If not, is there a more idiomatic (or simpler) solution that I missed? Something combining reduction and reduction of time?
Thanks.
clojure
Scott
source share