I would try to avoid last and but-last as they work in linear time. How about something like this?
(defn congeal-consecutives [coll] (when (seq coll) (let [[_ group res] (reduce (fn [[succ group res] n] (if (== succ n) [(inc n) (conj group n) res] [(inc n) [n] (conj res group)])) [(nth coll 0) [] []] coll)] (conj res group)))) > On Nov 6, 2014, at 5:22 PM, John Gabriele <jmg3...@gmail.com> wrote: > > Hi all, > > I've got this: `[1 3 4 5 7 9 10 11 12]` > and I'd like to turn it into this: `[[1] [3 4 5] [7] [9 10 11 12]]`. > > That is, I'd like to group consecutive numbers together (the final goal being > to produce something like `["1" "3-5" "7" "9-12"]`, but that's the easy part). > > I haven't found an easy way to do this. Here's what I've come up with in > Clojure: > > ~~~clojure > #!/usr/bin/env lein-exec > > (def v [1 3 4 5 7 9 10 11 12]) > > (defn congeal-consecutives > [coll] > (reduce (fn [accum x] > (if (= x (inc (last (last accum)))) > (concat (butlast accum) > [(conj (last accum) x)]) > (concat accum > [[x]]))) > [[(first coll)]] > (rest coll))) > > (prn (congeal-consecutives v)) -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.