Created
November 2, 2016 17:59
-
-
Save hadronzoo/c1e51ccdd3f657bc4399c6332e716b63 to your computer and use it in GitHub Desktop.
Partition contiguous groups of integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns xf.contiguous | |
(:require [clojure.data.int-map :as i])) | |
(defn partition-contiguous | |
([] | |
(let [buffer (volatile! (i/dense-int-set))] | |
(fn [xf] | |
(fn | |
([] (xf)) | |
([result] | |
(xf (let [rest @buffer] | |
(if (empty? rest) | |
result | |
(unreduced (xf result rest)))))) | |
([result item] | |
(let [contiguous @buffer | |
previous (last contiguous)] | |
(if (or (nil? previous) (== item (inc previous))) | |
(do (vswap! buffer conj item) | |
result) | |
(do (vreset! buffer (into (i/dense-int-set) [item])) | |
(if (empty? contiguous) | |
result | |
(xf result contiguous)))))))))) | |
([coll] | |
(sequence (partition-contiguous) coll))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment