Skip to content

Instantly share code, notes, and snippets.

@mping
Created December 10, 2018 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mping/b988ff1aaa9b16a3143e6d51b7b375ae to your computer and use it in GitHub Desktop.
Save mping/b988ff1aaa9b16a3143e6d51b7b375ae to your computer and use it in GitHub Desktop.
partition-while
(defn partition-while
"Given a coll, partition the coll whenever `(f a b)` returns `false`.
Example: `(partition-when #(<= 0 (Math/abs (- %1 %2)) 1) [1 2 3 5 6 8 10 10])
returns `[[1 2 3] [5 6] [8] [10 10]]`
"
([f coll] (partition-while f coll [] []))
([f [_ & t :as c] result intermediate]
(let [[a b & _] c]
(cond
(nil? a) result
(nil? b) (conj result (conj intermediate a))
(f a b) (recur f t result (conj intermediate a))
:else (recur f t (conj result (conj intermediate a)) [])))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment