On Thu, Nov 6, 2014 at 10:22 PM, John Gabriele <[email protected]> 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))
> ~~~
>
> Can anyone suggest a better / simpler / more easily-understandable way to do
> this in Clojure?
Hey John,
I think your approach is pretty good. I made some small modifications:
(defn congeal-consecutives
[xs]
(if (empty? xs)
[]
(reduce (fn [acc x]
(let [l (last acc)]
(if (= (inc (last l)) x)
(conj (pop acc) (conj l x))
(conj acc [x]))))
[[(first xs)]]
(rest xs))))
I didn't see how to use `partition-by` in a way that made the function
any clearer than the `reduce` version, but I'd be interested if you or
others do.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
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 [email protected].
For more options, visit https://groups.google.com/d/optout.