Skip to content

Instantly share code, notes, and snippets.

@brake
Last active January 19, 2016 15:03
Show Gist options
  • Save brake/034a5b87ef28783aeb79 to your computer and use it in GitHub Desktop.
Save brake/034a5b87ef28783aeb79 to your computer and use it in GitHub Desktop.
Turns sorted sequence of integers into list of number ranges in Clojure
(def a [1 2 3 4 6 8 9 11 12 13 14 20 21 23 24 25])
(loop [sq (rest a) fv (first a) lv (first a) res []]
(if (empty? sq)
(conj res [fv lv])
(if (= (- (first sq) lv) 1)
(recur (rest sq) fv (first sq) res)
(recur (rest sq) (first sq) (first sq) (conj res [fv lv])))))
=> [[1 4] [6 6] [8 9] [11 14] [20 21] [23 25]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment